Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray property initialization and updating

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;

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

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

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?

like image 301
Victor Engel Avatar asked Dec 06 '12 03:12

Victor Engel


1 Answers

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

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

EDIT:

After your edit,

NSInteger previousValue = [[_scores objectAtIndex:baseIndex] integerValue];
NSInteger updatedValue = previousValue + scoreAdjustmentAmount;
[_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];
like image 61
Anoop Vaidya Avatar answered Oct 20 '22 19:10

Anoop Vaidya