-1

配列があり、配列を反復処理するときに、アイテムも置き換えたいと思いました。これは不可能であり、そうするとクラッシュが発生しますか? コードは次のとおりです。

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];
}

これがObjective-Cで合法かどうか知りたいだけですか?そうでない場合、そうする代わりに何ができますか?

4

2 に答える 2

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;

テストはしていませんが、そのようなものです

于 2013-01-17T10:23:22.243 に答える
0

上記のコードは見栄えがします。

クラッシュした場合、それはアレイの変更によるものではありません。

ただし、古いスタイルのループ ( while、for(;;)、dowhile ) では、これらのいずれかを変更できます。

しかし、高速列挙の場合、これらすべてを行うことはできません。

したがって、上記のコードに for(... in ...) を組み込むと、不変オブジェクトを変更しようとしているというエラーがスローされます。カウンターや配列の不変高速列挙を定義しても、それらは不変として扱われます。

于 2013-01-17T07:05:40.030 に答える