开发者

Objective-C - How to compare arrays and extract the difference?

开发者 https://www.devze.com 2022-12-10 08:05 出处:网络
Possible duplicate: comparing-two-arrays I have two NSArray and I\'d like to create a new Array with objects from the second array but not

Possible duplicate: comparing-two-arrays

I have two NSArray and I'd like to create a new Array with objects from the second array but not included in the first array.

Example:

NSMutableArray *firstArray = [NSMutableArray ar开发者_JAVA百科rayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul", nil];

The resulting array should be: 

[@"Paul", nil];

I solved this problem with a double loop comparing objects into the inner one.

Is there a better solutions ?


[secondArray removeObjectsInArray:firstArray];

This idea was taken from another answer.


If duplicate items are not significant in the arrays, you can use the minusSet: operation of NSMutableSet:

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`


I want to compare images from two NSArray. One Array, I was getting from Core Database. Second I have constant array objects.

I want to know that object of second array is present in Core database or not.

Here is code which i used.

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

精彩评论

暂无评论...
验证码 换一张
取 消