开发者

NSArray safeguards

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 *myAr开发者_C百科ray;

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜