Reputation: 12675
In Objective-C, I need to initialize an array of nulls/nil ( not sure which one to use ).
I have this code:
NSMutableArray * ObjectIndex = [[NSMutableArray alloc] initWithCapacity:maxObjectId];
for ( int i = 0; i < maxObjectId; i++ )
{
[ObjectIndex setObject:nil atIndexedSubscript:i];
}
I'm getting an error stating that object cannot be nil.
I plan on using this array to store objects in at certain indexes, leaving others nil(null?)
Later in the code:
for (Object * obj in objs)
{
ObjectIndex[obj.ID] = obj;
}
Upvotes: 1
Views: 1940
Reputation: 4656
Simple! You can do it this way
NSMutableArray * ObjectIndex = [[NSMutableArray alloc] initWithCapacity: maxObjectId];
for(int i=0 ; i< maxObjectId ; i++) {
[ObjectIndex addObject:[NSNull null]];
}
Upvotes: 0
Reputation: 539775
That is what NSNull
is for. From the documentation:
The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).
So you can fill your array with [NSNull null]
instead of nil
:
for (int i = 0; i < maxObjectId; i++ )
{
ObjectIndex[i] = [NSNull null];
}
Because [NSNull null]
is a singleton object, you can check an array entry with
if ([ObjectIndex[i] isEqual:[NSNull null]]) {
// "empty"
}
Note: Names of Objective-C instance variables start usually with a lower case letter, so objectIndex
would be a better name.
Upvotes: 3
Reputation: 16215
Rather than use a sparse array, why not us an NSMutableDictionary with the numbers as keys? That way you don't have to worry about prepopulating With nulls.
Alternatively, if you really want to use an array, I'd suggest initializing with either addObject: or insertObject:atIndex:
Upvotes: 1