Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 766
Duck Avatar asked Apr 13 '26 00:04

Duck


1 Answers

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.

like image 172
Dave DeLong Avatar answered Apr 15 '26 14:04

Dave DeLong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!