Take the 2-minute tour ×

I have an non-mutable array that only needs to have numbers. How would I have to initialize this?

I have it like below right now but I'm thinking there has to be a better way. Can we do it like in C++? Something like this int list[5] = {1,2,3,4,5}; would that have any impact on the application?

myArray = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil];

Also, if I had a need for an array of arrays with only numbers, how would this look like? I'm new to obj-c and looking around online I've seen conflicting answers.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

If it is non-mutable and only contains numbers just use the C array directly. There is nothing wrong with using C arrays in Objective-C, and in your case an NSArray is just unneeded overhead.

share|improve this answer
Thanks, that's what i was hopping for. What about a two dimensional array? could we do it in C syntax also? –  user1213042 Feb 25 '12 at 2:47
As many dimensions as you like :-) –  CRD Feb 25 '12 at 4:55

Not yet, but soon:


Update: The new syntax is:

@[ @(20), @(10) ]

The @[] creates an array, the @(number) makes an NSNumber that can go in the array.

share|improve this answer

You could add a category to NSArray:

@implementation NSArray ( ArrayWithInts )

+(NSArray*)arrayWithInts:(const int[])ints count:(size_t)count
    assert( count > 0 && count < 100 ) ;    // just in case

    NSNumber * numbers[ count ] ;
    for( int index=0; index < count; ++index )
        numbers[ index ] = [ NSNumber numberWithInt:ints[ index ]] ;

    return [ NSArray arrayWithObjects:numbers count:count ] ;

countof() looks like this:


Use like this:

const int numbers[] = { 20, 10, 5, 2, 1, 0 } ;  
NSArray * array = [ NSArray arrayWithInts:numbers count:countof(numbers) ] ) ;

Or you could just use @CRD's suggestion above...

share|improve this answer

Your Answer

