If you want to make an array of integers, can you use NSInteger? Do you have to use NSNumber? If so, then why?
+3
A:
You can use a plain old C array:
NSInteger myIntegers[40];
for (NSInteger i = 0; i < 40; i++)
myIntegers[i] = i;
// to get one of them:
NSLog (@"The 4th integer is: %d", myIntegers[3]);
Or, you can use an NSArray
or NSMutableArray
, but here you will need to wrap up each integer inside an NSNumber
instance (because NSArray
objects are designed to hold class instances).
NSMutableArray *myIntegers = [NSMutableArray array];
for (NSInteger i = 0; i < 40; i++)
[myIntegers addObject:[NSNumber numberWithInteger:i]];
// to get one of them:
NSLog (@"The 4th integer is: %@", [myIntegers objectAtIndex:3]);
// or
NSLog (@"The 4th integer is: %d", [[myIntegers objectAtIndex:3] integerValue]);
dreamlax
2010-07-27 01:31:44
I think it's worth noting that C arrays are such a hassle for anything but trivial, one-off use that it's actually less trouble to wrap any arrays you plan on keeping around as NSArrays of NSNumber.
Chuck
2010-07-27 01:58:18
Yes, and given the [presumably] expert-level optimisations under the hood of `NSArray`, I'm sure you won't feel the performance hit.
dreamlax
2010-07-27 02:03:48
+2
A:
If you want to use a NSArray, you need an Objective-C class to put in it - hence the NSNumber requirement.
That said, Obj-C is still C, so you can use regular C arrays and hold regular ints instead of NSNumbers if you need to.
Dennis Munsie
2010-07-27 01:33:26