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;
}
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.
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.
arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With