Retrieve integers by looping through a NSMutableArray
Can someone show me how to retrieve values by looping through a NSMutableArray
? My code, which basically adds integer numbers to the array, is below :
NSMutableArray *ptr = [[NSMutableArray allo开发者_如何学运维c] init];
[ptr addObject:[NSNumber numberWithInt:1]];
[ptr addObject:[NSNumber numberWithInt:2]];
[ptr addObject:[NSNumber numberWithInt:3]];
// How to retrieve them as integers?
I'm trying to retrieve each number from the array and sum them up to a total value.
Its actually pretty simple:
int totalValue = 0;
for(NSNumber *number in myArray) // Use fast enumeration to iterate through the array
{
totalValue += [number intValue];
}
I'm also a newbie so my answer may be wrong, but try this:
int sum = 0;
for (int i = 0, i < [ptr count], i++){
int value = [[ptr objectAtIndex:i] intValue] //you get the int, integerValue is applicable for NSInteger
sum = sum + value;//you adding values
}
精彩评论