问题
I have an NSArray of objects, which have a property id
.
I then have another NSArray with a selection of ids.
I need to get all the objects in the first array which have the ids listed in the second array.
Is it possible to do this without for loops (well 1 for loop is ok, but I'd like to avoid it). I know how to do this with 2 for loops, but this seems very inefficient. So basically I'm looking for the most efficient way.
(The Id is an NSURL btw, so it can't be anything integer specific)
回答1:
No loops!
NSArray *arrayOfIdentifiers = ...;
NSArray *arrayOfObjects = ...;
NSPredicate *filter = [NSPredicate predicateWithFormat:@"id IN %@", arrayOfIdentifier];
NSArray *filteredObjects = [arrayOfObjects filteredArrayUsingPredicate:filter];
Well, no loops that you write. There are probably loops inside filteredArrayUsingPredicate:
.
回答2:
You need an intersection os sets.
NSMutableSet *set1=[[[NSMutableSet alloc] initWithArray:array1] autorelease];
NSMutableSet *set2=[[NSMutableSet alloc] initWithArray:array2];
[set1 intersectSet:set2];
[set2 release];
NSArray *newArray=[set1 allObjects];
来源:https://stackoverflow.com/questions/5526372/array-of-objects-from-array-passing-test