如何在NSMutableArray中迭代时删除NSDictionary

时间:2015-03-05 02:08:23

标签: ios objective-c nsdictionary nsmutabledictionary

我希望在名称相同时从数组中删除对象。这该怎么做?提前致谢。这是我的代码

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

当我编译时,我得到了这个错误  < __ NSArrayM:0x7fea39804f40>在被列举时被突变。'

2 个答案:

答案 0 :(得分:-1)

您需要做的是创建一个单独的可变数组。像这样:

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

此外,我不确定您使用uniqueArraySort做了什么,但如果您计划在之后使用它,则可能需要将其设为NSMutableArray

答案 1 :(得分:-1)

尝试这样的事情...我认为关键的价值"名称"可能是一个字符串。

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;

更新:第二个想法,我发现上面的代码仍然太多了。您可以使用哈希表在O(n)处执行此操作。

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;