2009-10-30 55 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是無效類型的。 – Adam 2012-11-07 13:43:34

+2

最後陳述正確的代碼只是「[secondSet minusSet:firstSet]。」它執行減法。結果不會返回,而是第二個對象的操作。如果這是一個子程序,那麼你會「返回secondSet」 – 2012-11-09 00:08:54

0

我想從兩個比較的NSArray圖像。 One Array,我是從核心數據庫中獲得的。其次我有不斷的數組對象。

我想知道第二陣列的該對象是存在於核心數據庫或沒有。

這裏是代碼,我使用。

// 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);