使用NSPredicate(可可)比较2个数组 [英] comparying 2 array's with NSPredicate (cocoa)
本文介绍了使用NSPredicate(可可)比较2个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NSObject带有2个属性的
i have an NSObject with 2 property's
@interface Entity : NSObject {
NSNumber *nid;
NSString *title;
}
我有2个数组,其中包含Entity的对象,我想在nid上将这两个数组与谓词进行比较
i have 2 array's with Entity's objects in it and I want to compare those two on the nid with a predicate
array1: ({nid=1,title="test"},{nid=2,title="test2"})
array2: ({nid=2,title="test2"},{nid=3,title="test3"})
这2个数组的nid都为2,所以我的输出应该是
the 2 arrays have both a nid with value 2 so my output should but
array3: ({nid=2,title="test2"})
所以我可以产生一个只有匹配的nid的数组
so i can produce an array with only matching nid's
推荐答案
以下代码似乎对我有用(它显然泄漏了MyEntity对象,但这不是示例目标):
The following code seems to work for me (it obviously leaks MyEntity objects but that was not the sample target):
NSArray* array1 = [NSArray arrayWithObjects:[[MyEntity alloc] initWithID:[NSNumber numberWithInt:1] title:@"1"],
[[MyEntity alloc] initWithID:[NSNumber numberWithInt:2] title:@"2"], nil];
NSArray* array2 = [NSArray arrayWithObjects:[[MyEntity alloc] initWithID:[NSNumber numberWithInt:2] title:@"2"],
[[MyEntity alloc] initWithID:[NSNumber numberWithInt:3] title:@"3"], nil];
NSArray* idsArray = [array1 valueForKey:@"nid"];
NSArray* filteredArray = [array2 filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"nid IN %@", idsArray]];
filteredArray
包含两个数组中都存在ID的实体.
filteredArray
contains entities whose ids present in both array.
这篇关于使用NSPredicate(可可)比较2个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文