【问题标题】:How to remove NSDictionary while iterating in NSMutableArray [duplicate]如何在 NSMutableArray 中迭代时删除 NSDictionary [重复]
【发布时间】:2015-03-05 02:08:22
【问题描述】:

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

    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:> 在被枚举时发生了变异。'

【问题讨论】:

标签: ios objective-c nsdictionary nsmutabledictionary


【解决方案1】:

尝试这样的事情......我假设键“name”的值可能是一个字符串。

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;

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      相关资源
      最近更新 更多