tags:

views:

159

answers:

2

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?

A: 

I think this is a question of programming style more than anything.

I'm guessing you're worried about allocating memory unnecessarily should a passed in array is empty

djhworld
Exactly, besides not wanting to accidentally access an empty array I also don't want a useless variable taking up space.
Spider-Paddy
+1  A: 

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 the nil array to an NSArray, NSDictionary or other collection class, the runtime will throw an exception.

Rob Keniger
I thought setting to nil was the safe thing to do?!? I'll remember what you've said, thanks.
Spider-Paddy