2009-10-30 6 views
21

중복 : comparing-two-arraysObjective-C - 배열을 비교하고 차이점을 추출하는 방법은 무엇입니까? 가능한

나는이있는 NSArray를하고 난 두 번째 배열에서 객체와 새로운 배열을 만들 수 있지만, 첫 번째 배열에 포함되지 싶습니다.

Example: 

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil]; 
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul", nil]; 

The resulting array should be: 

[@"Paul", nil]; 

이 문제는 객체를 내부 루프와 비교하는 이중 루프로 해결되었습니다.

더 좋은 솔루션이 있습니까?

답변

93
[secondArray removeObjectsInArray:firstArray]; 

이 아이디어는 another answer에서 찍은.

10

중복 항목이 배열에서 하지 중요한 경우에, 당신은 NSMutableSetminusSet: 작업을 사용할 수 있습니다

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil]; 
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul", nil]; 

NSSet *firstSet = [NSSet setWithArray:firstArray]; 
NSMutableSet *secondSet = [NSMutableSet setWithCapacity:[secondArray count]]; 
[secondSet addObjectsFromArray:secondArray]; 

[secondSet minusSet:firstSet]; // result is in `secondSet` 
+2

이것은 불가능합니다. Apple의 문서에 따르면 minusSet은 void 타입입니다. – Adam

+2

마지막 문장의 올바른 코드는 "[secondSet minusSet : firstSet];"입니다. 뺄셈을 수행합니다. 결과는 반환되지 않고 secondSet 객체에 대한 연산입니다. 이것이 서브 루틴에 있다면, "return set second;" –

0

두 NSArray의 이미지를 비교하고 싶습니다. 하나의 어레이, 코어 데이터베이스에서 가져 왔습니다. 둘째, 상수 배열 객체가 있습니다.

두 번째 배열의 개체가 코어 데이터베이스에 있는지 여부를 알고 싶습니다.

여기에 내가 사용한 코드가 있습니다.

// All object from core data and take into array. 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"student"]; 

NSArray *dbresult = [[NSArray alloc]init]; 
NSError *error; 
@try { 
    dbresult = [context executeFetchRequest:fetchRequest error:&error]; 
} 
@catch (NSException *exception) { 
    NSString *logerror = [NSString stringWithFormat:@"error in fetching Rooms from coredata = %@",exception.description]; 
NSLog(logerror) 
} 
@finally { 
} 

/* 
Get Unused images from list 
*/ 

NSMutableArray *usedImages = [dbresult valueForKey:@"roomImageLocalPath"]; 

NSMutableSet *fSet = [NSMutableSet setWithArray:usedImages]; 
NSMutableSet *sSet = [NSMutableSet setWithCapacity:[newImages count]]; 
[sSet addObjectsFromArray:newImages]; 
[sSet minusSet:fSet]; 

NSArray *unusedImages = [secondSet allObjects]; 
NSLog(@"unusedImages %@",unusedImages); 
관련 문제