1

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;
}
1
  • Have you tried [ObjectIndex setObject:@"" atIndexedSubscript:i]; ??? Commented Dec 12, 2012 at 6:47

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

0

Simple! You can do it this way

NSMutableArray * ObjectIndex = [[NSMutableArray alloc] initWithCapacity: maxObjectId];
for(int i=0 ; i< maxObjectId ; i++) {
    [ObjectIndex addObject:[NSNull null]];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.