Initializing an NS Array of Numbers

I have a non-moving array that should only have numbers. How should I initialize this?

I have it like below right now, but I think there should be a better way. Can we do it like in C ++? Something like this int list[5] = {1,2,3,4,5}; would affect the application?

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

Also, if I needed an array of arrays with only numbers, what would it look like? I am new to obj-c and looked around, I saw conflicting answers.

+4
source share
3 answers

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

+5
source

Not yet, but soon:

http://blog.ablepear.com/2012/02/something-wonderful-new-objective-c.html

Update: new syntax:

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

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

+6
source

You can 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 ] ; } @end 

countof() as follows:

 #define countof(x) (sizeof(x)/sizeof(x[0])) 

Use this:

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

Or you could just use the @CRD clause above ...

-one
source

Source: https://habr.com/ru/post/1398329/


All Articles