开发者

Object from NSUserDefaults releasing?

开发者 https://www.devze.com 2023-01-27 21:35 出处:网络
So I have a us开发者_运维知识库ername saved in the UserDefaults.For some reason, I am experiencing some strange behavior.

So I have a us开发者_运维知识库ername saved in the UserDefaults. For some reason, I am experiencing some strange behavior.

I have a data controller that goes and fetches some data from the server based on the user name.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(@"NSUserDefaults dump: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

userID = [prefs stringForKey:@"username"];

This works fine for the first few times, but after I do some random stuff and go back to try and reload the views, it crashes. It says:

-[CFString retain]: message sent to deallocated instance 0x4b18ff0

This is strange because it is stopping on the NSLog line. Has anyone seen this before or know why it may be happening??


How you defined your userID? If it's a property with a retain attribute you should call

self.userID = [prefs stringForKey:@"username"];

this way your string will be retained automatically. The string that is returned from stringForKey is autoreleased.


stringForKey returns an autorelease object which you aren't retaining, it's probably released as soon as that method finishes.

You need to retain that string either by doing so manually or using a property declaration with the retain setting.

And then you need to release it at some point (at least in dealloc)

0

精彩评论

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