How do you save an integer to NSUserDefaults?

后端 未结 2 1381
甜味超标
甜味超标 2020-12-03 01:26

Does anyone know how I would go about saving my high score integer to NSUserDefaults so I can load it later?

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 01:50

    More generally, you can save Foundation class objects to the user defaults, e.g.:

    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"kHighScore"];
    

    and

    NSInteger highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kHighScore"] intValue];
    

    But the convenience method is there for taking in an NSInteger directly.

    I prefer to use the more agnostic -setObject: and -objectForKey: because it more cleanly separates the object type from access to the dictionary.

提交回复
热议问题