迭代和替换项目同时

时间:2013-01-17 04:39:06

标签: iphone ios objective-c ipad

我有一个数组,当我遍历数组时,我也想替换该项目。这是不可能的,如果我这样做会引起痉挛吗?这是代码:

for (int i = 0; i < [highlightItemsArray count]; i++){
   //replace the from array with the new one
   NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionaryWithDictionary:highlightItem];
   [tempDictionary setObject:[newHighlightItem objectForKey:@"from"] forKey:@"from"];
   [highlightItemsArray replaceObjectAtIndex:i withObject:tempDictionary];
   [indexes addIndex:i];
}

只是想知道这在目标C中是否合法?如果没有,那么这样做的替代方案是什么?

2 个答案:

答案 0 :(得分:0)

上面的代码看起来不错。

如果它崩溃,则不是因为你的阵列改变了。

然而,在旧式循环中(而对于(;;),dowhile),您可以更改其中的任何一个    1.初始化(但只执行一次)    柜台    3.条件。

但是在快速枚举的情况下,你不能做所有这些。

因此,如果将上面的代码与for(... in ...)合并,则会抛出错误,说试图改变不可变对象。即使你定义了你的计数器和/或数组,不可变的快速枚举也将它们视为不可变的。

答案 1 :(得分:0)

解决这个问题的快速而肮脏的方法是数组副本,即

NSMutableArray *higlightItemsCopy = [highlightItemsArray mutableCopy];
for (int i = 0; i < [highlightItemsArray count]; i++){
   //replace the from array with the new one
   NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionaryWithDictionary:highlightItem];
   [tempDictionary setObject:[newHighlightItem objectForKey:@"from"] forKey:@"from"];
   higlightItemsCopy[i] = tempDictionary;
   [indexes addIndex:i];
}
highlightItemsArray = higlightItemsCopy;

没有测试过,但有类似的东西

相关问题