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?
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.
arrays can't contain nil.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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...
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With