Array of objects from array passing test

早过忘川 提交于 2019-12-12 18:15:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!