简体   繁体   English

NSMutableArray属性的初始化和更新

[英]NSMutableArray property initialization and updating

Suppose I have a @property that is an NSMutablearray that is to contain scores used by four objects. 假设我有一个@property,它是一个NSMutablearray,它包含四个对象使用的分数。 They will be initialized as zero and then updated during viewDidLoad and throughout operation of the app. 它们将被初始化为零,然后在viewDidLoad和应用程序的整个操作过程中进行更新。

For some reason, I can't wrap my mind around what needs to be done, particularly at the declaration and initialization steps. 由于某些原因,我无法确定需要做些什么,特别是在声明和初始化步骤上。

I believe this can be a private property. 我相信这可以是私人财产。

@property (strong, nonatomic) NSMutableArray *scores;

@synthesize scores = _scores;

Then in viewDidLoad I try something like this but get an error. 然后,在viewDidLoad中,我尝试执行类似操作,但出现错误。 I just need help with syntax, I think. 我认为我只需要语法方面的帮助。 Or I'm missing something very basic. 或者我缺少一些非常基本的东西。

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

Is that an appropriate way to initialize it? 那是初始化它的合适方法吗? Then how do I add (NSNumber *)updateValue to, say, the nth value? 然后如何将(NSNumber *)updateValue添加到第n个值?

Edit: I think I figured it out. 编辑:我想我想通了。

-(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]];
}

Is there a better way of doing this? 有更好的方法吗?

You are initializing in viewDidLoad , However you should do it in init . 您正在viewDidLoad进行初始化,但是应该在init中进行init

These both are similar, and perfectly valid. 这两者是相似的,并且完全有效。

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

or, 要么,

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

Your last question... Then how do I add (NSNumber *)updateValue to, say, the nth value? 您的最后一个问题... Then how do I add (NSNumber *)updateValue to, say, the nth value? If you addObject: it will be added at last. 如果您添加addObject:它将最后添加。 You need to insertObject:atIndex: in your required index, and all following objects will shift to next indices. 您需要在所需索引中insertObject:atIndex:所有随后的对象将移至下一个索引。

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

EDIT: 编辑:

After your edit, 编辑后,

NSInteger previousValue = [[_scores objectAtIndex:baseIndex] integerValue];
NSInteger updatedValue = previousValue + scoreAdjustmentAmount;
[_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM