我有一个问题,我无法理解。我有一个 NSUserDefaults 实例,并在其中存储了一些值。其中一个值是一个数组,其中包含要在另一个显示中使用的玩家得分(它是一个游戏)。游戏完成后,我用新分数更新数组并将其重新分配给 NSUserDefaults,但由于某种原因,当我尝试将计数打印到控制台时,它似乎表现不正确并且在调试中,它总是0。
这是有问题的代码:
// // SAMHighScoreInputViewController.m // Tappity // // Created by Sam on 29/05/13. // Copyright (c) 2013 Sam. All rights reserved. //
#import "SAMHighScoreInputViewController.h"
#import "SAMScoreObject.h"
@interface SAMHighScoreInputViewController ()
@end
@implementation SAMHighScoreInputViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self; }
- (void)viewDidLoad {
self.defaults = [NSUserDefaults standardUserDefaults];
self.nameScoreLabel.text = [NSString stringWithFormat:@"%@ - %@", [self.defaults objectForKey:@"lastName"], [self.defaults objectForKey:@"lastScore"]];
self.nameTextField.text = [self.defaults objectForKey:@"lastName"];
[super viewDidLoad]; // Do any additional setup after loading the view. }
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (IBAction)textFieldValueChanged:(UITextField *)sender {
self.nameScoreLabel.text = [NSString stringWithFormat:@"%@ - %@", self.nameTextField.text, [self.defaults objectForKey:@"lastScore"]];
}
- (IBAction)submitButtonTapped:(UIButton *)sender {
SAMScoreObject *score = [[SAMScoreObject alloc] init];
score.playerName = self.nameTextField.text;
score.score = [self.defaults integerForKey:@"lastScore"];
NSArray *scores = [self.defaults objectForKey:@"scoresArray"];
NSMutableArray *updatedArray = [scores mutableCopy];
[updatedArray addObject:score];
NSArray *updatedArrayScores = [updatedArray copy];
[self.defaults setObject:updatedArrayScores forKey:@"scoresArray"];
[self.defaults setObject:[self.defaults objectForKey:@"scoresArray"] forKey:@"scoresArray"];
[self.defaults synchronize];
NSLog(@"%@, %@", [self.defaults objectForKey:@"lastScore"], [self.defaults objectForKey:@"lastName"]);
NSLog(@"%i", [[self.defaults objectForKey:@"scoresArray"] count]);
[self dismissViewControllerAnimated:YES completion:nil];
} @end