티스토리 뷰

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.

-------------------

Have a look at this post.

In short: if you can use NSSet instead of NSArray, then it's trivial (NSMutableSet has intersectSet:).

Otherwise, you can build an NSSet from your NSArray and go back to the above case.

-------------------

NSMutableArray *first = [[NSMutableArray alloc] initWithObjects:@"Jack", @"John", @"Daniel", @"Lisa",nil];

NSMutableArray *seconds =[[NSMutableArray alloc] initWithObjects:@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica",nil];

NSMutableArray *third = [ [ NSMutableArray alloc]init];


for (id obj in first) {

    if ([seconds  containsObject:obj] ) {
    
    
            [third addObject:obj];
            
                }
                
                
                }
                
                
                NSLog(@"third is : %@ \n\n",third);
                

산출:

세 번째는 : (

Jack,

Lisa

) -------------------
이것은

NSSet

접근 방식 보다 깨끗 하며 원래 주문을 잃지 않을 것입니다.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self IN %@ AND self IN %@", array2, array3];
NSArray *array4 = [array1 filteredArrayUsingPredicate:predicate];

-------------------
위의 링크에서 작동하는 변형이 있습니다.

NSPredicate *intersectPredicate = [NSPredicate predicateWithFormat:@"SELF IN %@", @[@500, @400, @600]];
NSArray *intersect = [@[@200, @300, @400] filteredArrayUsingPredicate:intersectPredicate];



출처
https://stackoverflow.com/questions/39949978

댓글
공지사항
Total
Today
Yesterday
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31