If there is a chance that an NSArray is empty, is it better to check it and set equal to nil if it’s empty when it is assigned or to rather do the check when it is used?
e.g.
NSArray *myArray;
if ([anotherArray count] > 0) <-- Check when assigned
myArray = [anotherArray copy];
else
myArray = nil;
something = [myArray objectAtIndex:x];
or
NSArray *myArray;
myArray = [anotherArray copy];
if ([myArray count] > 0) <-- Check when used
something = [myArray objectAtIndex:x];
Which is better?
You should just check to see if the array is empty when necessary.
Don’t set it to
nil, this can cause other problems. For example, if you try to add thenilarray to anNSArray,NSDictionaryor other collection class, the runtime will throw an exception.