Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 同时迭代和替换项_Iphone_Ios_Objective C_Ipad - Fatal编程技术网

Iphone 同时迭代和替换项

Iphone 同时迭代和替换项,iphone,ios,objective-c,ipad,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:highlig

我有一个数组,当我遍历该数组时,我也想替换该项。如果我这样做,这是不可能的,并且会导致崩溃吗?代码如下:

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];
}
for(int i=0;i<[highlightItemsArray count];i++){
//将from阵列替换为新阵列
NSMutableDictionary*tempDictionary=[NSMutableDictionary Dictionary WithDictionary:highlightItem];
[tempDictionary setObject:[newHighlightItem objectForKey:@“from”]forKey:@“from”];
[highlightItemsArray replaceObjectAtIndex:i with Object:tempDictionary];
[索引addIndex:i];
}

只是想知道这在objective-C中是否合法?如果没有,那么还有什么办法呢?

您上面的代码看起来不错

如果它崩溃,则不是由于更改了阵列造成的

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

但在快速枚举的情况下,您无法完成所有这些操作


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

解决这一问题的快捷方法是数组副本,即

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;
NSMutableArray*higlightItemsCopy=[highlightItemsArray mutableCopy];
对于(int i=0;i<[highlightItemsArray count];i++){
//将from阵列替换为新阵列
NSMutableDictionary*tempDictionary=[NSMutableDictionary Dictionary WithDictionary:highlightItem];
[tempDictionary setObject:[newHighlightItem objectForKey:@“from”]forKey:@“from”];
HiglightItemScope[i]=临时字典;
[索引addIndex:i];
}
highlightItemsArray=HighlightItems透视;

还没有测试过它,但是类似的东西不会导致任何崩溃。只有在使用“快速枚举”(数组{}中的id对象的
)时,这才会失败。也许有一种更简单的方法来完成你正在做的事情,但我不确定你到底想实现什么