我有一個問題,我不能讓我的頭。我有一個NSUserDefaults的實例,並在那裏存儲了一些值。其中一個值是一個數組,其中包含要在另一個顯示中使用的玩家分數(其遊戲)。遊戲結束後,我用新分數更新陣列並將其重新分配給NSUserDefaults,但出於某種原因,它似乎沒有正確運行,並且在調試時我嘗試將計數打印到控制檯中,但始終0NSUserDefaults數組沒有正確保存
這裏是有問題的代碼:
// // 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
我沒有看到錯誤,但我建議對代碼進行兩項改進:1)將數組的另一個副本並將其分配給'updatedArrayScores'的步驟是不必要的,只需將'updatedArray'直接傳遞給' NSUserDefaults'。 2)你可以完全刪除語句'[self.defaults setObject:[self.defaults objectForKey:@「scoresArray」] forKey:@「scoresArray」];'。 – herzbube
'self.defaults'設置屬性如何?你確定保留它。如果它沒有被保留,那麼在你發送'setObject:forKey:'和'synchonize'方法之前它可能已經被釋放,並且它會失敗。 – lukestringer90