Reputation: 15245
i have an NSObject with 2 property's
@interface Entity : NSObject {
NSNumber *nid;
NSString *title;
}
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"})
the 2 arrays have both a nid with value 2 so my output should but
array3: ({nid=2,title="test2"})
so i can produce an array with only matching nid's
Upvotes: 3
Views: 750
Reputation: 170839
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
contains entities whose ids present in both array.
Upvotes: 4