Get Integer value from NSNumber in NSArray

Phill Pafford picture Phill Pafford · Aug 1, 2012 · Viewed 15.6k times · Source

I have an NSArray with NSNumber objects that have int values:

arrayOfValues = [[[NSArray alloc] initWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:3], [NSNumber numberWithInt:5], [NSNumber numberWithInt:6], [NSNumber numberWithInt:7], nil] autorelease];
[arrayOfValues retain];

I'm trying to iterate through the array like this:

int currentValue;
for (int i = 0; i < [arrayOfValues count]; i++)
{
    currentValue = [(NSNumber *)[arrayOfValues objectAtIndex:i] intValue];
    NSLog(@"currentValue: %@", currentValue); // EXE_BAD_ACCESS
}

What am I doing wrong here?

Answer

sosborn picture sosborn · Aug 1, 2012

You are using the wrong format specifier. %@ is for objects, but int is not an object. So, you should be doing this:

int currentValue;
for (int i = 0; i < [arrayOfValues count]; i++)
{
    currentValue = [(NSNumber *)[arrayOfValues objectAtIndex:i] intValue];
    NSLog(@"currentValue: %d", currentValue); // EXE_BAD_ACCESS
}

More information in the docs.