开发者

Combining NSArrays Through Intersection and Union

开发者 https://www.devze.com 2023-04-09 11:47 出处:网络
I have two NSArrays A and B that share some common elements, e.g. A: 1,2,3,4,5 B: 4,5,6,7 I would like to create a new NSArray consisting of the contents common between the two NSArrays joined wit

I have two NSArrays A and B that share some common elements, e.g.

A: 1,2,3,4,5 
B: 4,5,6,7

I would like to create a new NSArray consisting of the contents common between the two NSArrays joined with the contents of the second NSArray while maintaining the order of the elements and removing duplicates. That is, I would like (A ∩ B) ∪ B.

The operation on the previous NSArrays would yield:

A ∩ B: 4,5
(A ∩ B) ∪ B: 4,5,6,7

How do I accomp开发者_JS百科lish this in Objective-C?


Convert the NSArrays to NSSets, the standard set operations are available.

NSArray *a = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
NSArray *b = [NSArray arrayWithObjects:@"4", @"5", @"6", @"7", nil];

NSMutableSet *setA = [NSMutableSet setWithArray:a];
NSSet *setB = [NSSet setWithArray:b];
[setA intersectSet:setB];
NSLog(@"c: %@", [setA allObjects]);

NSLog output: c: (4, 5)

[setA unionSet:setB];
NSLog(@"d: %@", [setA allObjects]);

NSLog output: d: (6, 4, 7, 5)


As others have suggested, you can easily do this with NSSet. However, this will not preserve ordering.

If you want to preserve ordering and you can target OS X 10.7+, then you can use the new NSOrderedSet (and mutable subclass) to do the same thing.


By using NSSet, as others have pointed out. For

NSArray * a = [NSArray arrayWithObjects: ... ];
NSArray * b = [NSArray arratWithObjects: ... ];
NSMutableSet * set = [NSMutableSet setWithArray:a];
[set intersectSet:[NSSet setWithArray:b];
[set unionSet:[NSSet setWithArray:b];

This takes care of dupes but won't preserve order. You'd take the results in "set" and sort them back into an array. There's no native collection functionality that will do it all-- if you prefer to keep the order and worry about dupes separately, use NSMutableArray's -removeObjectsInArray: method, etc.


(A ∩ B) ∪ B will always give you B, so this is a pretty bizarre thing to want to calculate. It's like saying "Give me the set of all cars that are colored green, combined with the set of all cars". That's going to give you the set of all cars.


There is an NSSet class you can use to perform these operations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号