Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

iphone - Finding Intersection of NSMutableArrays

I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

NSMutableArray *array1 = [@"Jack", @"John", @"Daniel", @"Lisa"];
NSMutableArray *array2 = [@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica"];
NSMutableArray *array3 = [@"Jack", @"Jerome", @"Dan", @"Lindsay", @"Lisa"];

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

NSMutableArray *array4 = [@"Jack",@"Lisa"];

Because all the three array have jack and lisa as an element. Is there way of simply doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

The only issue with this is that you lose ordering of elements, but I think (in this case) that that's OK.


As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 added a new class called NSOrderedSet (with a Mutable subclass) that allows you to perform these same intersection operations while still maintaining order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...