Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the result of passing just nil to arrayWithArray:?

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?

like image 219
Chris Wagner Avatar asked May 22 '12 22:05

Chris Wagner


1 Answers

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.

like image 60
Richard J. Ross III Avatar answered Oct 05 '22 12:10

Richard J. Ross III