Search code examples
objective-ciositeratornsarraynsnumber

Get Integer value from NSNumber in NSArray


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?


Solution

  • 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.