0

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.

dmaulikr
  • 458
  • 5
  • 20
Jason lau
  • 111
  • 2
  • 9

4 Answers4

3

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.

Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
0

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];
ggmathur
  • 833
  • 5
  • 12
  • Hi ggmathur, When I change to self.myArray = [array mutableCopy], I get the endless result.Do you know why ? Thanks Eg.1234,1234,1234,1234,1234,1234,1234.... – Jason lau Jul 17 '13 at 07:01
0

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.

Manish Agrawal
  • 10,958
  • 6
  • 44
  • 76
0

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]];
}
Syed Absar
  • 2,274
  • 1
  • 26
  • 45