Reputation: 111
I am new to iOS development, I encounter error when replaceObjectAtIndex. Any wrong with my codes? Please help.Thanks.
self.myArray =array;
for (NSDictionary *data in array) {
NSString *fbid = [data objectForKey:@"id"];
for (int index = 0; index < self.myPersonArray.count; index ++) {
for (IP_PERSON *person in self.myPersonArray) {
if ([person.UserDef2 isEqualToString:fbid]) {
[self.myArray replaceObjectAtIndex:index withObject:person];
break;
}
}
}
Error is :
Terminating app due to uncaught exception NSGenericException
, reason: '*** Collection <__NSArrayM: 0xa34f6c0> was mutated while being enumerated.
Upvotes: 0
Views: 608
Reputation: 2284
You can..
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]
self.myArray =array;
for (NSDictionary *data in array) {
NSString *fbid = [data objectForKey:@"id"];
for (int index = 0; index < self.myPersonArray.count; index ++) {
for (IP_PERSON *person in self.myPersonArray) {
if ([person.UserDef2 isEqualToString:fbid]) {
[dictionary setObject:person forKey:@(index)]; //Notice this line
break;
}
}
}
}
And then..
for(id key in dictionary) {
[self.myArray replaceObjectAtIndex:[key intValue] withObject:[dictionary objectForKey:key]];
}
Upvotes: 0
Reputation: 11026
You can take another temporary array and iterate over that array, so you are enumerating and mutating different array.
NSArray *tempArray = [yourArray copy]; for (IP_PERSON *person in tempArray) { if ([person.UserDef2 isEqualToString:fbid]) { [self.myArray replaceObjectAtIndex:index withObject:person]; break; } } [tempArray release];
Alternatively you can iterate without an enumerator, you can use regular for loop with starting index, exit condition and increment as you have done in outer loop.
Upvotes: 0
Reputation: 843
You're iterating over array
, which is equal to self.myArray
.
Further down, you're editing this array when you do: [self.myArray replaceObjectAtIndex:index withObject:person];
To resolve this, just make self.array
a mutableCopy of the original array:
self.myArray = [array mutableCopy];
Upvotes: 0
Reputation: 32414
You cannot use fast enumeration and mutate collection at the same time, hence the error message. You can resort to using an usual for-loop.
Upvotes: 3