Search code examples
objective-ciosnsarraynsnumber

Initializing NSArray of numbers


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.


Solution

  • 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.