5

假设我有一个 @property,它是一个 NSMutablearray,它包含四个对象使用的分数。它们将被初始化为零,然后在 viewDidLoad 和应用程序的整个操作过程中更新。

出于某种原因,我无法完全考虑需要做什么,尤其是在声明和初始化步骤。

我相信这可以是私有财产。

@property (strong, nonatomic) NSMutableArray *scores;

@synthesize scores = _scores;

然后在 viewDidLoad 我尝试这样的事情但得到一个错误。我想我只需要语法方面的帮助。或者我错过了一些非常基本的东西。

self.scores = [[NSMutableArray alloc] initWithObjects:@0,@0,@0,@0,nil];

这是初始化它的合适方法吗?那么如何将 (NSNumber *)updateValue 添加到第 n 个值?

编辑:我想我想通了。

-(void)updateScoreForBase:(int)baseIndex byIncrement:(int)scoreAdjustmentAmount
{
    int previousValue = [[self.scores objectAtIndex:baseIndex] intValue];
    int updatedValue = previousValue + scoreAdjustmentAmount;
    [_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];
}

有没有更好的方法来做到这一点?

4

1 回答 1

5

您正在初始化viewDidLoad,但是您应该在init.

这两者是相似的,并且完全有效。

_scores = [[NSMutableArray alloc] initWithObjects:@0,@0,@0,@0,nil]; 

或者,

self.scores=[[NSMutableArray alloc]initWithObjects:@0,@0,@0, nil];

你的最后一个问题......Then how do I add (NSNumber *)updateValue to, say, the nth value? 如果你addObject:最后会添加它。您需要insertObject:atIndex:在所需的索引中,并且所有后续对象都将转移到下一个索引。

 NSInteger nthValue=12;
[_scores insertObject:updateValue atIndex:nthValue];

编辑:

编辑后,

NSInteger previousValue = [[_scores objectAtIndex:baseIndex] integerValue];
NSInteger updatedValue = previousValue + scoreAdjustmentAmount;
[_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];
于 2012-12-06T04:14:35.080 回答