Initialize NSArray with size

How to initialize an NSArray with a size only to use a for loop to populate it later? My cycle will be

for (int i = 0; i < [myArray count]; i++) { myArray[i] = someData; } 
+5
source share
2 answers

You do not need to initialize it with a specific size - you can add objects later:

 NSMutableArray * myArray = [NSMutableArray array]; for (int i = 0; i < 100; i++) { [myArray addObject:someData]; } 

There are small performance gains if you know the size in advance:

 NSMutableArray * myArray = [NSMutableArray arrayWithCapacity:100]; 

But this is optional.

+5
source

NSNull is a class used to represent an undefined, invalid, or nonexistent object. Therefore, you can put an array at a specific size using instances of this class.

 NSUInteger sizeOfArray = 10; NSMutableArray *someArray = [NSMutableArray array]; for (NSUInteger i = 0; i < sizeOfArray; i++) { [someArray addObject:[NSNull null]]; } 

Also, you cannot use the syntax someArray[i] = xyz; if the value at position i does not exist, as this will lead to an error outside the bounds.

+2
source

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


All Articles