0

我有一个问题,我无法理解。我有一个 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
4

2 回答 2

2

您需要先将其序列SAMScoreObject化为NSData某种形式的对象,然后才能将其存储在NSUserDefaults商店中。

文档中:

默认对象必须是一个属性列表,即以下实例(或集合实例的组合):NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary。如果要存储任何其他类型的对象,通常应该将其归档以创建 NSData 的实例。

您存储对象的事实还NSArray不够好,因为该数组中的对象不是受支持的类型之一。

于 2013-05-30T11:23:10.597 回答
1

scoresArray曾经创造在哪里?当您尝试更新它时,您可能应该懒惰地创建它。例如:

NSArray *scores = [self.defaults objectForKey:@"scoresArray"];
if(scores == nil)
{
    scores = [NSArray array];
}
NSMutableArray *updatedArray = [scores mutableCopy];
于 2013-05-30T10:51:29.910 回答