我正在寻找一种方法来比较两个NSMutableArray对象的内容。两个数组都填充了NSMutableDictionaries,它们是单独分配的,但偶尔也包含相同的数据。
简化示例:
NSMutableArray *firstArray = [[NSMutableArray alloc] init];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];
NSMutableDictionary *a = [[NSDictionary alloc] init];
[a setObject:@"foo" forKey:"name"];
[a setObject:[NSNumber numberWithInt:1] forKey:"number"];
NSMutableDictionary *b = [[NSDictionary alloc] init];
[b setObject:@"bar" forKey:"name"];
[b setObject:[NSNumber numberWithInt:2] forKey:"number"];
NSMutableDictionary *c = [[NSDictionary alloc] init];
[c setObject:@"foo" forKey:"name"];
[c setObject:[NSNumber numberWithInt:1] forKey:"number"];
[firstArray addObject:a];
[firstArray addObject:b];
[secondArray addObject:c];
a,b和c是不同的对象,但a和c的内容匹配。
我正在寻找的是比较firstArray和secondArray并仅返回b的函数/方法。
在伪代码中:
NSArray *difference = [self magicFunctionWithArray:firstArray andArray:secondArray];
NSLog(@"%@",difference)
=> ({name="bar"; number=2})
提前谢谢。
答案 0 :(得分:6)
这可以使用NSMutableSet
个实例来实现。
NSMutableSet * firstSet = [NSMutableSet setWithArray:firstArray];
NSMutableSet * secondSet = [NSMutableSet setWithArray:firstArray];
[firstSet unionSet:[NSSet setWithArray:secondArray]];
[secondSet intersectSet:[NSSet setWithArray:secondArray]];
[firstSet minusSet:secondSet];
NSLog(@"%@", firstSet);