views:

73

answers:

1

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

+1  A: 

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.

Vladimir
NSArray* idsArray = [array1 valueForKey:@"nid"]; doesn't work, *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSDecimalNumber 0x4e679f0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key nid.'
Andy Jacobs
That must mean that some objects in your array are not MyEntity objects or were corrupted somehow...
Vladimir
all my objects are entity objects and i don't know how they can be corrupted because when i log nid it shows up perfectly
Andy Jacobs
So you've tried iterating through your array and call nid on each element? May be you could post more code where you create and fill your array... Error message shows that NSDecimalNumber object receives nid message for some reason - that must imply that it is in your array
Vladimir
it (finally) works, do have any idea to the opposite ? to get all the objects from array 1 that doesn't match any nid in array2 ?
Andy Jacobs