Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Phill Pafford Avatar asked Aug 01 '12 03:08

Phill Pafford


People also ask

Is NSNumber integer?

NSNumber provides readonly properties that return the object's stored value converted to a particular Boolean, integer, unsigned integer, or floating point C scalar type.

Can Nsarray contain nil?

arrays can't contain nil.

What is Nsarray Objective C?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Is Nsarray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


2 Answers

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.

like image 193
sosborn Avatar answered Oct 20 '22 21:10

sosborn


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!

like image 45
jungledev Avatar answered Oct 20 '22 21:10

jungledev