2009-10-30 50 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);