22

I have two arrays . Array1 contains 15 objects and Array2 contains 4 objects. There are 2 common objects from both array, I just want to get that resulted array of that 2 objects.

It should be like intersection of two Set, but how to do in Objective C for array..? Please help. thanks.

Dishant
  • 917
  • 2
  • 8
  • 25

1 Answers1

56

Using NSMutableSet

NSMutableSet *set1 = [NSMutableSet setWithArray: array1];
NSSet *set2 = [NSSet setWithArray: array2];
[set1 intersectSet: set2];
NSArray *resultArray = [set1 allObjects];
jcesarmobile
  • 51,328
  • 11
  • 132
  • 176
  • 1
    Here set1 should be NSMutableSet because NSMutableSet has extension intersectSet method – Paresh Navadiya Aug 29 '12 at 09:15
  • 2
    how well does this work if these arrays are pretty big, like 2000 objects each? Is this a scalable solution? – zumzum Jul 15 '14 at 04:17
  • It's worth saying why one would use NSSet for efficiency reasons! The code using NSSets will perform faster (better runtime efficiency) than the for loop equivelant. – occulus Aug 21 '14 at 09:28
  • @Akhrameev I'm rejecting your edit suggestion as in any place is being asked to order the set. Feel free to add your suggestion as a new answer – jcesarmobile Dec 15 '16 at 08:08