problem with loading from NSUserDefaults, obj-c
I'm having a problem with NSUserDefaults. I'm saving a name, then trying to access it later in the code from another view controller, but it seems that my key is empty or not saved as when I display the string from the key my label is blank.
-(void) saveName {
NSString *name = nameField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:name forKey:@"playersName"];
[defaults synchronize];
}
-(void) viewDidLoad // method called later on in code from different viewcontroller
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *name = [defaults objectForKey:@"playersName"];
playerName.text = name; // player name == myLabel
if ([[NSUsersDefaults standardUserDefaults] objectForKey:@"playersName"] == n开发者_开发知识库il) {
playerName.text =@" blank";
}
}
My string doesn't seem to be saving to userdefaults as the @"blank" string keeps showing up with my label. I'm not too familiar with NSUserDefaults so any help is much appreciated.
A few things to note when using NSUserDefaults
:
- calls to syncrhonize method is not necesary and will only make it slower if your program is multi threaded.
- Check if the key that you use is being used by other libraries in your project
- Check if the value that you set to the key is not nil
- Try to use
stringForKey:
orboolForKey:
instead ofobjectForKey:
I had troubles a few times with NSUserDefaults but in the end it's usually my code that's problematic.
I would suggest you to check whether your '(void) saveName' method is being called or not... Put some breakpoint and see the result
精彩评论