What is NSString in struct?

Posted by 4thSpace on Stack Overflow See other posts from Stack Overflow or by 4thSpace
Published on 2009-12-29T06:15:54Z Indexed on 2010/04/19 8:53 UTC
Read the original article Hit count: 380

I've defined a struct and want to assign one of its values to a NSMutableDictionary. When I try, I get a EXC_BAD_ACCESS. Here is the code:

//in .h file
typedef struct {
NSString *valueOne;
NSString *valueTwo;
}  myStruct;

myStruct aStruct;

//in .m file
- (void)viewDidLoad {
[super viewDidLoad];
aStruct.valueOne = @"firstValue";
}

//at some later time
[myDictionary setValue:aStruct.valueOne forKey:@"key1"]; //dies here with EXC_BAD_ACCESS

This is the output in debugger console:

(gdb) p aStruct.valueOne
$1 = (NSString *) 0xf41850

Is there a way to tell what the value of aStruct.valueOne is?

Since it is an NSString, why does the dictionary have such a problem with it?

------------- EDIT -------------

This edit is based on some comments below.

The problem appears to be in the struct memory allocation. I have no issues assigning the struct value to the dictionary in viewDidLoad, as mentioned in one of the comments. The problem is that later on, I run into an issue with the struct. Just before the error, I do:

po aStruct.oneValue

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00000000
0x9895cedb in objc_msgSend ()
The program being debugged was signaled while in a function called from GDB.
GDB has restored the context to what it was before the call.
To change this behavior use "set unwindonsignal off"
Evaluation of the expression containing the function (_NSPrintForDebugger) will be   abandoned.

This occurs just before the EXC_BAD_ACCESS:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yy_HH-mm-ss-A"];
NSString *date = [formatter stringFromDate:[NSDate date]];
[formatter release];

aStruct.valueOne = date;

So the memory issue is most likely in my releasing of formatter. The date var has no retain. Should I instead be doing

NSString *date = [[formatter stringFromDate:[NSDate date]] retain];

Which does work but then I'm left with a memory leak.

© Stack Overflow or respective owner

Related posts about iphone

Related posts about iphone-sdk