Get Integer value from NSNumber in NSArray
Asked Answered
B

2

6

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?

Broadcaster answered 1/8, 2012 at 3:48 Comment(0)
Q
18

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.

Quasijudicial answered 1/8, 2012 at 3:54 Comment(3)
I thought %@ was a wild card so I could pass anythingBroadcaster
You can pass any object, but like I said, int is not an object.Quasijudicial
thanks, this does help with clarification and the error. having a DOH! (slap hand on head) momentBroadcaster
W
1

This worked for me when creating an NSArray of enum values I wanted to call (which is useful to know that this is the proper solution for that) I'm using Xcode 6.4.

int currentValue = (int)[(NSNumber *)[arrayOfValues objectAtIndex:i] integerValue];

sosborn's answer will throw a warning since it is still necessary to cast the NSInteger to an int.

Typecasting in ObjC is the bane of my existence. I hope this helps someone!

Winstonwinstonn answered 7/8, 2015 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.