如何在NSMutableDictionary中找到重复项?

时间:2012-11-21 23:58:12

标签: ios nsarray nsdictionary nsmutabledictionary

伪代码:

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”}。

2 个答案:

答案 0 :(得分:3)

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包含一个数组,其值显示在all:

duplicates=(
  mike,
  george
)

答案 1 :(得分:-1)

假设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];
}