Comparing NSMutableArray Elements for Values

℡╲_俬逩灬. 提交于 2019-12-12 09:08:53

问题


I am looking for a way to compare the contents of two NSMutableArray objects. Both arrays are filled with NSMutableDictionaries which were allocated separately but occasionally contain the same data.

Simplified Example:

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 and c are distinct object, but the contents of a and c match.

What I am looking for is a function / approach to compare firstArray and secondArray and return only b.

In Pseudocode:

NSArray *difference = [self magicFunctionWithArray:firstArray andArray:secondArray];
NSLog(@"%@",difference)

=> ({name="bar"; number=2})

Thank you in advance.


回答1:


This can be achieved using NSMutableSet instances.

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


来源:https://stackoverflow.com/questions/6346750/comparing-nsmutablearray-elements-for-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!