NSMutableArray属性初始化和更新

Vic*_*gel 5 initialization nsmutablearray nsinteger ios

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

出于某种原因,我无法理解需要做的事情,特别是在声明和初始化步骤中.

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

@property (strong, nonatomic) NSMutableArray *scores;

@synthesize scores = _scores;
Run Code Online (Sandbox Code Playgroud)

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

self.scores = [[NSMutableArray alloc] initWithObjects:@0,@0,@0,@0,nil];
Run Code Online (Sandbox Code Playgroud)

这是初始化它的合适方式吗?然后我如何将(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]];
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

Ano*_*dya 5

你正在初始化viewDidLoad,但你应该这样做init.

这两者都相似,完全有效.

_scores = [[NSMutableArray alloc] initWithObjects:@0,@0,@0,@0,nil]; 
Run Code Online (Sandbox Code Playgroud)

要么,

self.scores=[[NSMutableArray alloc]initWithObjects:@0,@0,@0, nil];
Run Code Online (Sandbox Code Playgroud)

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

 NSInteger nthValue=12;
[_scores insertObject:updateValue atIndex:nthValue];
Run Code Online (Sandbox Code Playgroud)

编辑:

编辑完成后

NSInteger previousValue = [[_scores objectAtIndex:baseIndex] integerValue];
NSInteger updatedValue = previousValue + scoreAdjustmentAmount;
[_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];
Run Code Online (Sandbox Code Playgroud)