js_
js_

Reputation: 4731

arrayWithArray:nil returns empty array but not documented

NSArray and NSMutableArray's +arrayWithArray: returns empty array instead of nil when argument is nil.

    NSLog(@"%@", [[NSArray arrayWithArray:nil] class]);
    NSLog(@"%@", [[NSMutableArray arrayWithArray:nil] class]);

output:

    __NSArrayI
    __NSArrayM

But this behavior is not documented on Apples documentation.

Is it safe to rely on the assumption that arrayWithArray:nil returns empty array?
Or should I assign empty array explicitly like this:

    NSDictionary *dic = [[NSDictionary alloc] init];
    NSMutableArray *arr = [dic objectForKey:@"a"];
    if (!arr) {
        arr = [[NSMutableArray alloc] init];
    }

Upvotes: 3

Views: 646

Answers (1)

Martin R
Martin R

Reputation: 539945

The documentation of +arrayWithArray: says:

Creates and returns an array containing the objects in another given array.

Of course, nil is not an array, but [nil count] is valid and returns 0, so it might be treated as an empty array here.

But I would not rely on that fact and create empty arrays with [[NSMutableArray alloc] init] or [NSMutableArray array].

ADDED:

If you call +arrayWithArray: with an invalid type, e.g. a NSString, then of course the program will throw an exception. But from the error message

-[__NSCFConstantString count]: unrecognized selector sent to instance 0x69e4

you can see that count is indeed the first method used to copy the array elements. That also explains why it works with nil.

Upvotes: 5

Related Questions