NSArray guarantees

If there is a chance the NSArray is empty, is it better to check it and set it to nil if it is empty when it is assigned, or rather do a check when it is used?

eg.

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

      

What's better?

+2


a source to share


2 answers


You just need to check if the array is not there if needed.



Do not install it on nil

, it may cause other problems. For example, if you try to add an array nil

to NSArray

, NSDictionary

or another collection class, the runtime will throw an exception.

+3


a source


I think this is the programming style question the most.



I assume you are worried about unnecessary memory allocation if passed in array is empty

0


a source







All Articles