Map array 2 to NSPredicate (cocoa)

I have an NSObject with 2 property

@interface Entity : NSObject  {

     NSNumber *nid;
     NSString *title;
}

I have 2 arrays with Entity objects in it and I want to compare these two on nid with a predicate

array1: ({nid=1,title="test"},{nid=2,title="test2"})
array2: ({nid=2,title="test2"},{nid=3,title="test3"})

2 arrays have nid with value 2, so my output should be

array3: ({nid=2,title="test2"})

so I can create an array with a suitable nid

+3
source share
1 answer

The following code seems to work for me (it clearly loses MyEntity objects, but that was not the 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 objects whose identifiers are present in both arrays.

+4
source

Source: https://habr.com/ru/post/1746363/


All Articles