NSArray 保障措施
如果 NSArray 有可能为空,那么是在分配它时检查它并设置为空(如果它是空的)还是在使用它时进行检查更好?
例如
NSArray *myArray;
if ([anotherArray count] > 0) <-- Check when assigned
myArray = [anotherArray copy];
else
myArray = nil;
something = [myArray objectAtIndex:x];
或
NSArray *myArray;
myArray = [anotherArray copy];
if ([myArray count] > 0) <-- Check when used
something = [myArray objectAtIndex:x];
哪个更好?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在必要时检查数组是否为空。
不要将其设置为
nil
,这可能会导致其他问题。例如,如果您尝试将nil
数组添加到NSArray
、NSDictionary
或其他集合类,运行时将引发异常。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 thenil
array to anNSArray
,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