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