Duck
Duck

Reputation: 35993

iphone - mutableArray cannot store nil objects

I have a mutable array that is retained and storing several objects. At some point, one object may become nil. When this happens the app will crash, because arrays cannot have nil objects. Imagine something like

[object1, object2, object3, nil];

then, object2 = nil

[object1, nil, object3, nil];

that is not possible because nil is the end of array marker. So, how can I solve that? thanks for any help.

Upvotes: 3

Views: 479

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243156

Use [NSNull null] if you have to store an empty placeholder object.

For example:

NSArray * myArray = [NSArray arrayWithObjects:obj1, [NSNull null], obj3, nil];

myArray will contain 3 objects. When you retrieve the object, you can do a simple pointer equality test to see if it's the Null singleton:

id object = [myArray objectAtIndex:anIndex];
if (object == [NSNull null]) {
  //it's the null object
} else {
  //it's a normal object
}

EDIT (responding to a comment)

@Mike I think you're getting confused with what's actually going on.

If you have:

id obj = ...;

Then obj contains an address. It does not contain an object. As such, if you do NSLog(@"%p", obj), it'll print something like 0x1234567890. When you put obj into the array, it's not copying the object, it's copying the address of the object. So the array actually contains 0x1234567890. Therefore, when you later do: obj = nil;, you're only affecting the pointer outside of the array. The array will still contain 0x1234567890.

Upvotes: 9

Related Questions