NSMutableArray属性的初始化和更新 [英] NSMutableArray property initialization and updating

查看:677
本文介绍了NSMutableArray属性的初始化和更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a @property that is an NSMutablearray that is to contain scores used by four objects. They will be initialized as zero and then updated during viewDidLoad and throughout operation of the app.

由于某些原因,我无法确定需要做些什么,特别是在声明和初始化步骤上.

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;

然后在viewDidLoad中尝试这样的操作,但出现错误.我认为我只需要语法方面的帮助.或者我缺少一些非常基本的东西.

Then in viewDidLoad I try something like this but get an error. 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];

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

Is that an appropriate way to initialize it? Then how do I add (NSNumber *)updateValue to, say, the nth value?

我想我想通了.

-(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中进行该操作.

You are initializing in viewDidLoad, However you should do it in init.

这两个都是相似的,并且完全有效.

These both are similar, and perfectly valid.

_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:,随后的所有对象都将移至下一个索引.

Your last question... Then how do I add (NSNumber *)updateValue to, say, the nth value? If you addObject: it will be added at last. You need to insertObject:atIndex: in your required index, and all following objects will shift to next indices.

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

这篇关于NSMutableArray属性的初始化和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆