views:

525

answers:

3

Alright, I have my code, and I believe I have narrowed down the crashing bug to one section. Upon the view loading, my code loads the NSUserDefaults and pulls the string out of them. It then works with teh string. The problem is, I'm not sure how to pull the string out.

Here is the relative code:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *nameOne = [prefs stringForKey:@"playerOne"];
NSString *nameTwo = [prefs stringForKey:@"playerTwo"];

//do stuff with the strings

[nameOne release];
[nameTwo release];

Here is also the code for when I put the strings into the NSUserDefaults, on another View:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *tempName = [[NSString alloc] initWithFormat:@"You"];
[prefs setObject:tempName forKey:@"playerOne"];
NSString *tempName2 = [[NSString alloc] initWithFormat:@"Opponent"];
[prefs setObject:tempName2 forKey:@"playerTwo"];
[prefs synchronize];

I have isolated the issue to where I take the strings out of NSUserDefaults. I feel like I am taking them out wrong, but I'm not sure how else to do it. Using StringForKey may be wrong... or not allocating space? I'm not sure what the issue is, I've tried fixing it but to no avail. Help would be appreciated!

+1  A: 

You might want to check whether the strings you get from NSUserDefaults are autoreleased. I seem to remember that they are.

Frank Schmitt
Well, I removed the "release" statements, and that seemed to have cleared up the problem. Who knew! Thank you for your help!! Is there any way of knowing before hand if something is going to be autoreleased?
Wayfarer
@Wayfarer http://stackoverflow.com/questions/811547/is-it-right-to-say-that-methods-whoose-names-contain-new-alloc-create-or-copy-d/814236#814236
epatel
+1  A: 

I believe you should copy the strings like below (or remove the release lines)

NSString *nameOne = [[prefs stringForKey:@"playerOne"] copy];
NSString *nameTwo = [[prefs stringForKey:@"playerTwo"] copy];
epatel
A: 

To add Frank Schmitt's answer:

The general rule of thumb is if you don't see alloc or copy in the method's name, you can assume the caller doesn't have ownership of the object being returned, unless it explicitly calls retain. So often times the returned object will be placed on the autorelease pool.

So in this case "stringForKey" the calling function doesn't have ownership of the return value, so it doesn't need to call release.

And if you want to keep around the string after the calling functions leaves scope you will need to call retain. (Though judging by your release statements you don't)

I would familiarize yourself with: http://developer.apple.com/iphone/library/documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html

Eld