【问题标题】:How to find the duplicates in NSMutableDictionary? [closed]如何在 NSMutableDictionary 中查找重复项? [关闭]
【发布时间】:2012-11-10 08:05:57
【问题描述】:

伪代码:

NSArray *arr1 = {"mike","george","Tim","Tom"...}
NSArray *arr2 = {"mike","george","Chris","Adam"...}
NSArray *arr3 = {"Don","george","mike","Tom"...}
NSArray *arr4 = {"george","Nicole","Moe","mike"...}

//Add these arrays to the dictionary
for(int i=0; i<n, i++)
   [dictionary addObject:arr[i]];

我想找到所有数组中存在的重复值,而不是一些。 在本例中,值为 {"george","mike"}。

【问题讨论】:

  • 您是指所有数组共有的元素吗?此外,这是如何工作的,NSDictionary 没有方法“addObject:”。你的字典对象也是 NSArray 吗?
  • 对不起它的 NSMutableDictionary - 是的,所有数组都通用。

标签: ios nsarray nsdictionary nsmutabledictionary


【解决方案1】:
NSArray *arr1 = @[@"mike",@"george",@"Tim",@"Tom" ];
NSArray *arr2 = @[@"mike",@"george",@"Chris",@"Adam" ];
NSArray *arr3 = @[@"Don",@"george",@"mike",@"Tom" ];
NSArray *arr4 = @[@"george",@"Nicole",@"Moe",@"mike" ];

NSMutableSet *intersection = [NSMutableSet setWithArray:arr1];
[intersection intersectSet:[NSSet setWithArray:arr2]];
[intersection intersectSet:[NSSet setWithArray:arr3]];
[intersection intersectSet:[NSSet setWithArray:arr4]];

NSArray *duplicates = [intersection allObjects];

NSLog(@"duplicates=%@", duplicates);

duplicates 包含一个数组,其中包含所有出现的值:

duplicates=(
  mike,
  george
)

【讨论】:

  • 谢谢-这是我接受的另一种简单方法之外的方法。我试过这个方法,效果也很好。
【解决方案2】:

假设dictionary 实际上是一个 NSMutableArray,那么这样的事情会起作用:

NSMutableArray *results = [[NSMutableArray alloc] init];

for(NSString *name in [dictionary objectAtIndex:0]) {
    bool valid = true;
    for(int i=1;i<[dictionary count];i++) {
        if([[dictionary objectAtIndex:i] indexOfObject:name]==NSNotFound) {
            valid=false;
            break;
        }
    }
    if(valid)
        [results addObject:name];
}

【讨论】:

  • 太棒了 - 我的代码使用了 NSMutableDictionary,但我能够进行更改。
  • [NSMutableDictionaryInstance values] 或 [NSMutableDictionaryInstance keys] 将产生一个 NSArray 供您使用上面的 for 循环遍历。
  • @SMA2012,您应该直截了当地了解您的术语——您没有可变字典,否则此代码将不起作用。你所拥有的是一个可变数组。
  • @rdelmar- 以上是伪代码。我有一个 mutableDictionary,它工作正常。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 2021-08-16
相关资源
最近更新 更多