3

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];
    }

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You'll find this has since been updated with nullability info (largely for Swift), and the compiler / static analyzer will now complain about a nil argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.