NSArray safeguards
        Posted  
        
            by Spider-Paddy
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Spider-Paddy
        
        
        
        Published on 2010-05-06T10:42:49Z
        Indexed on 
            2010/05/06
            10:48 UTC
        
        
        Read the original article
        Hit count: 366
        
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?
© Stack Overflow or respective owner