What happens when you pass nil
to arrayWithArray:
?
Let's say I have the following code:
NSMutableArray *myArray = [NSMutableArray arrayWithArray:someOtherArray];
If someOtherArray
happens to be nil
, will myArray
be nil
or will it be an empty mutable array?
An empty array is returned.
An example implementation of +arrayWithArray:
would be the following:
+(id) arrayWithArray:(NSArray *) arr
{
NSMutableArray *returnValue = [NSMutableArray new];
returnValue->objectsCount = [arr count];
returnValue->objectsPtr = malloc(sizeof(id) * returnValue->objectsCount);
[arr getObjects:returnValue->objectsPtr range:NSMakeRange(0, returnValue->objectsCount)];
return returnValue;
}
Thus, if arr
is null, -count
returns 0, nothing is malloc
'd, and nothing is copied, because a message sent to a nil object returns the default return value for that type, and does nothing else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With