简体   繁体   中英

Increment a value in an int NSMutableArray

I've an NSMutableArray as

self.valuesArray = [[NSMutableArray alloc]initWithObjects:[NSNumber numberWithInt: 0],[NSNumber numberWithInt: 0],[NSNumber numberWithInt: 0],[NSNumber numberWithInt: 0], nil];

As you can see it's initialized with 0 now If I want to increment 3 at index 2 how can I do it? I was trying to do it like

self.valuesArray[2] = [self.valuesArray objectAtIndex:2]+3;

but that's not the right way.

I've also tried doing this

[self.valuesArray[2] addObject:[NSNumber numberWithInt:[self.valuesArray[2] intValue]+3]];

but I got error that:

Unrecognized selector sent to instance

You should do like this it will work.

int valueInc = [[self.valuesArray objectAtIndex:2] intValue] + 2;
NSNumber *numberValue = [NSNumber numberWithInt:valueInc];

[self.valuesArray replaceObjectAtIndex:2 withObject:numberValue];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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