Objective-C 2.0和Fast Enumeration抛出异常 [英] Objective-C 2.0 and Fast Enumeration throwing exceptions

查看:280
本文介绍了Objective-C 2.0和Fast Enumeration抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下代码块:

I have a block of code which is similar to the following:

for (NSDictionary *tmp in aCollection) {
   if ([[bar valueForKey:@"id"] isEqualToString:[tmp valueForKey:@"id"]])
   {
      break;
   }
   else
   {
      [aCollection addObject:bar];
       }
 }


$ b <它似乎你不能突变集合与快速枚举。这是错误的结果:

Is this technically an exception in Objective-C 2.0? It appears you cannot mutate a collection with fast enumeration. This is the result of an error:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <NSCFArray: 0x396000> was mutated while being enumerated.'

最好的解决方法是什么?

What's the best way to solve this?

推荐答案

很好的解决方法是不要改变数组(例如添加一个对象),同时枚举它:)

Well the way to solve it is not to mutate the array (e.g. add an object) while enumerating it :)

这里的问题是,通过添加/删除元素修改数组可能会导致枚举值无效,因此它是一个问题。

The problem here is that modifying the array by adding/removing elements could cause the enumeration values to become invalid, hence why it's a problem.

在你的情况下解决这个问题的最简单的方法是修复你的代码中的错误。你的代码为数组中的每个项目做else add子句,我确定这不是你想要的。

In your case The easiest way to solve this is fixing the bug in your code. Your code is doing the "else add" clause for every item in the array and I'm quite sure that's not what you want.

尝试此操作;

bool found = false;
for (NSDictionary *tmp in aCollection)
{
   if ([[bar valueForKey:@"id"] isEqualToString:[tmp valueForKey:@"id"]])
   {
      found = true;
      break;
   }
}

if (!found)
{
 [aCollection addObject:bar];
}

这篇关于Objective-C 2.0和Fast Enumeration抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆