-1

I want to remove object from array when the name is same. How to do this? Thanks in advance. Here is my code

    NSString *name1;
    NSString *name2;

    NSArray *copyArray = [uniqueArraySort copy];
    for (NSMutableDictionary *dict1 in copyArray) {
        for (NSDictionary *dict2 in uniqueArraySort) {
            name1 = [dict1 valueForKey:@"name"];
            name2 = [dict2 valueForKey:@"name"];
            if ([name1 isEqualToString:name2]) {
                NSLog(@"%@",uniqueArraySort);
            [uniqueArraySort removeObject:dict2];
                NSLog(@"%@",uniqueArraySort);
            }
        }
    }

And when I compile I get this error <__NSArrayM: 0x7fea39804f40> was mutated while being enumerated.'

Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109
apple8
  • 33
  • 8

2 Answers2

-1

What you need to do is create a separate mutable array. Something like this:

NSMutableArray *itemsToDelete = [NSMutableArray array];

NSMutableArray *copyArray = [uniqueArraySort mutableCopy];

for (NSMutableDictionary *dict1 in copyArray) {
    for (NSDictionary *dict2 in uniqueArraySort) {
        name1 = [dict1 valueForKey:@"name"];
        name2 = [dict2 valueForKey:@"name"];
        if ([name1 isEqualToString:name2]) {
            NSLog(@"%@",uniqueArraySort);
          [itemsToDelete addObject:dict2];
            NSLog(@"%@",uniqueArraySort);
        }
    }
}
[copyArray removeObjectsInArray:itemsToDelete];

Also, I'm not sure what you are doing with uniqueArraySort but you might need to make that an NSMutableArray if you plan on using it after.

MendyK
  • 1,643
  • 1
  • 17
  • 30
-1

Try something like this... I assume value for key "name" might be a string.

NSSet *set = [NSSet setWithArray:[uniqueArraySort valueForKey:@"name"]];
NSMutableArray *array = [NSMutableArray new];
for (NSString* value in set.allObjects) {
    NSArray *filteredArray = [uniqueArraySort filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", value]];
    if(filteredArray.count > 0)
        [array addObject:[filteredArray firstObject]];
}

return array;

UPDATE : On second thought, I found that code above is still too much. You can do it at O(n) using hashtable.

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:uniqueArraySort.count];
for(NSDictionary *item in uniqueArraySort)
{
    NSString *name = [item objectForKey:@"name"];
    if([dictionary objectForKey:name] == nil)
    {
         [dictionary setObject:item forKey:name];
    }
}

return dictionary.allValues;
Wonjae
  • 309
  • 2
  • 6