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:Of course,
nilis not an array, but[nil count]is valid and returns0, 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. aNSString, then of course the program will throw an exception. But from the error messageyou can see that
countis indeed the first method used to copy the array elements. That also explains why it works withnil.