我有一个问题我无法理解。我有一个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
答案 0 :(得分:2)
您需要将SAMScoreObject
序列化为某个表单的NSData
对象,然后才能将其存储在NSUserDefaults
商店中。
默认对象必须是属性列表,即(或集合的实例组合)的实例:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。如果要存储任何其他类型的对象,通常应将其存档以创建NSData实例。
您存储NSArray
对象的事实不够好,因为该数组中的对象不是受支持的类型之一。
答案 1 :(得分:1)
scoresArray
曾在哪里创建过?当您尝试更新它时,您可能应该懒洋洋地创建它。例如:
NSArray *scores = [self.defaults objectForKey:@"scoresArray"];
if(scores == nil)
{
scores = [NSArray array];
}
NSMutableArray *updatedArray = [scores mutableCopy];