Ios NSMutableArray属性初始化和更新

Ios NSMutableArray属性初始化和更新,ios,nsmutablearray,initialization,nsinteger,Ios,Nsmutablearray,Initialization,Nsinteger,假设我有一个@property,它是一个NSMutablearray,包含四个对象使用的分数。它们将被初始化为零,然后在viewDidLoad期间和整个应用程序运行期间更新 出于某种原因,我无法集中精力考虑需要做什么,特别是在声明和初始化步骤 我相信这可以是私人财产 @property (strong, nonatomic) NSMutableArray *scores; @synthesize scores = _scores; 然后在viewDidLoad中,我尝试了类似的操作,但出现了

假设我有一个@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]];
}

有更好的方法吗?

您正在
viewDidLoad
中初始化,但是您应该在
init
中进行初始化

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

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

你的最后一个问题<代码>那么如何将(NSNumber*)updateValue添加到第n个值中? 如果您
addObject:
它将在最后被添加。您需要在所需索引中
插入对象: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]];

我不确定我是否理解这个问题你到底在问什么?您是否尝试过在实现文件(
.m
)中声明它,并在
viewDidLoad
方法(
self.myMutableArray=[[NSMutableArray alloc]init];
)中初始化它?您需要更详细地描述一下您可以在init方法或viewDidLoad中分配数组,或者使用“随需应变”命令getter方法中的分配器。一旦分配了它,任何拥有指向包含对象的指针的人都可以引用该属性(如果是公共的)并读/写数组。在向我的问题添加代码时,我意识到我的关键问题是混合了NSMutableArray和NSArray,这会生成警告,让我觉得我出了严重错误。但我想我的想法是对的。谢谢。我将把代码移到init。我不想移动数组元素。我只是想更新一下,我出错了“指向指向+的NSNumber指针的算术运算。此外,您使用的是_分数,而不是分数。你的意思是这样吗?我在编辑后更新了文本:。关键的项目是我从NSNumber转换为int,然后进行计算,然后在更新数组之前转换为NSNumber。好的。。我还没有编译,只是输入了:p,我建议使用像NSInteger这样的包装类,应该避免使用原始数据类型。self.scores表示您正在使用访问器。你可以使用它们中的任何一个,除非你正在做一些绑定的东西。
NSInteger previousValue = [[_scores objectAtIndex:baseIndex] integerValue];
NSInteger updatedValue = previousValue + scoreAdjustmentAmount;
[_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];