开发者

problem with loading from NSUserDefaults, obj-c

开发者 https://www.devze.com 2023-04-02 10:23 出处:网络
I\'m having a problem with NSUserDefaults. I\'m saving a name, then trying to access it laterin the code from another view controller, but it seems that my key is empty or not saved as when I display

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:

  1. calls to syncrhonize method is not necesary and will only make it slower if your program is multi threaded.
  2. Check if the key that you use is being used by other libraries in your project
  3. Check if the value that you set to the key is not nil
  4. Try to use stringForKey: or boolForKey: instead of objectForKey:

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

0

精彩评论

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