Darthg8r
Darthg8r

Reputation: 12675

Initialize Empty Array

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

Answers (3)

Asif Mujteba
Asif Mujteba

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

Martin R
Martin R

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

Krease
Krease

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

Related Questions