NSArray 保障措施

发布于 2024-08-31 11:48:48 字数 479 浏览 1 评论 0原文

如果 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

划一舟意中人 2024-09-07 11:48:48

您应该在必要时检查数组是否为空。

不要将其设置为nil,这可能会导致其他问题。例如,如果您尝试将 nil 数组添加到 NSArrayNSDictionary 或其他集合类,运行时将引发异常。

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.

暮年慕年 2024-09-07 11:48:48

我认为这首先是编程风格的问题。

我猜您担心如果传入的数组为空,则会不必要地分配内存

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文