So I have multiple NSArrays(5 actually), and I would like to create a new NSArray containing only objects common to ALL arrays. Is there an efficient way to d开发者_如何学Pythono this. The only way I can think of, is to loop through all the arrays comparing each object.
I ended up using this which works quite well:
NSMutableSet *set = [NSMutableSet setWithArray:array];
NSMutableSet *set1 = [NSMutableSet setWithArray:array2];
NSMutableSet *set2 = [NSMutableSet setWithArray:array3];
NSMutableSet *set3 = [NSMutableSet setWithArray:array4];
NSMutableSet *set4 = [NSMutableSet setWithArray:array5];
[set intersectSet:set1];
[set intersectSet:set2];
[set intersectSet:set3];
[set intersectSet:set4];
NSArray *allArray = [set allObjects];
Why not create an NSSet (NSMutableSet, really), dump the contents of all 5 arrays into it, and then construct a new NSArray from the NSSet?
Sorry, I misread your question originally. Yes, I think you pretty much have to loop through each one to find the duplicates. But it's not so terrible to implement (might be somewhat slow at runtime if your arrays are huge, however).
Here's some example code:
- (void) filterSet: (NSMutableSet*)set withArray: (NSArray*) array {
NSMutableSet* removals = [NSMutableSet setWithCapacity:[array count]];
for (id obj in set) {
if (! [array containsObject: obj]) {
[removals addObject: obj];
}
}
[set minusSet: removals];
}
NSMutableSet* mySet = [NSMutableSet setWithCapacity:[array1 count] * 5];
[mySet addObjectsFromArray: array1];
[self filterSet: mySet withArray: array2];
[self filterSet: mySet withArray: array3];
[self filterSet: mySet withArray: array4];
[self filterSet: mySet withArray: array5];
NSArray* filteredArray = [mySet allObjects];
精彩评论