【问题标题】:NSMutableArray property initialization and updatingNSMutableArray 属性初始化和更新
【发布时间】:2012-12-06 03:40:51
【问题描述】:

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

有更好的方法吗?

【问题讨论】:

  • 我不确定我是否理解问题
  • 你到底在问什么?你有没有试过在你的实现文件中声明它(.m)并在你的viewDidLoad方法中初始化它(self.myMutableArray = [[NSMutableArray alloc]init];)?
  • 你需要多一点描述性
  • 您可以在您的 init 方法或 viewDidLoad 或其他方法中分配数组,或者在 getter 方法中使用“按需”分配器。一旦它被分配,任何拥有指向包含对象的指针的人都可以引用该属性(如果是公共的)并读/写数组。
  • 在向我的问题添加代码时,我意识到我的关键问题是将 NSMutableArray 和 NSArray 混合在一起,这会产生警告,让我觉得我有什么可怕的错误。但我认为我的总体思路是对的。

标签: ios nsmutablearray initialization nsinteger


【解决方案1】:

您正在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]];

【讨论】:

  • 谢谢。我将代码移动到init。我不想移动数组元素。我只是想更新它们。
  • 我收到一个错误“指向 NSNumber 的指针指向 + 的算术运算。另外,您使用的是 _scores 而不是分数。您的意思是这样做吗?
  • 我在编辑后更新了文本:。关键项是我从 NSNumber 转换为 int,然后进行数学运算,然后在更新数组之前转换为 NSNumber。
  • ok.. 我还没有编译,只是输入了 :p 我建议使用像 NSInteger 这样的包装类,应避免使用原始数据类型。
  • _scores 表示您正在直接使用属性。 self.scores 表示您正在使用访问器。除非你正在做一些绑定的事情,否则你可以使用它们中的任何一个。
猜你喜欢
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
相关资源
最近更新 更多