开发者

How to pull a string out from NSUserDefaults

开发者 https://www.devze.com 2022-12-16 08:45 出处:网络
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

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 h开发者_开发问答ow 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!


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


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];


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号