Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize NSArray with size

How do I initialize an NSArray with size only so to use a for loop to fill it later? My for loop would be

for (int i = 0; i < [myArray count]; i++) {
    myArray[i] = someData;
}
like image 418
Katedral Pillon Avatar asked Dec 09 '14 00:12

Katedral Pillon


People also ask

How do you declare NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

Is NSArray ordered?

The workhorse of collection types is the array. In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.


2 Answers

You don't 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 slight performance gains if you know the size ahead of time:

NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:100];

But this is optional.

like image 134
Aaron Brager Avatar answered Oct 23 '22 15:10

Aaron Brager


NSNull is the class used to represent an unset, invalid or non-existent object. Therefore you can pad the array to 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]];
}

Further, you can't use the syntax someArray[i] = xyz; if the value at position i doesn't exist, as it will cause an out of bounds error.

like image 41
max_ Avatar answered Oct 23 '22 13:10

max_