开发者

Saving/Loading Data with NSUserDefaults (cocos2d iphone)

I have an Upgrades scene where 开发者_StackOverflowthe user can upgrade different attributes of the game, and I want that information to be saved. For example, when the user spends 1000 points to upgrade the mag by 5, I want that information to be saved for the next launch of the app. I've been told NSUserDefaults is a good way to do this. Is this the right way of correctly saving/loading the mag int?

-(void)plusFiveMag:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:NSNumber numberWithInt:mag forKey:@"mag"];
    mag += 5; 
}   
-(void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:NSNumber numberWithInt:mag forKey:@"mag"];
}


Using accessors makes this all so much easier. Using accessors means you never have to worry about how mag is stored internally, so you can transparently store it in NSUserDefaults rather than in an ivar.

@property (nonatomic, readonly, assign) NSUInteger mag;

NSString * const kMagDefaultsKey = @"mag";

- (NSUInteger)mag {
  return [[NSUserDefaults standardUserDefaults] integerForKey:kMagDefaultsKey];
}

- (void)setMag:(NSUInteger)value {
  [[NSUserDefaults standardUserDefaults] setInteger:value forKey:kMagDefaultsKey];
}

- (void)addFiveToMag:(id)sender {
  self.mag = self.mag + 5;
}


Store it like this:

-(void)plusFiveMag:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:mag forKey:@"mag"];
    mag += 5; 
} 

To get it you would have to use:

-(void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    int mag = [defaults integerforKey:@"mag"];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜