I have 2 NSArrays of 2 different types of custom objects.
Object A properties: ID: Name: Author:
Object B Properties: bookID: value: terminator:
I need to filter an array of objects of type "A" that has the ID value equal to the bookID value of any of the objects of the second array that contains objects of type "B".
I tried to use the intersectSet: method by converting the arrays to sets, but since both the objects are of different type, nothing happened.
What will be the most efficient way to do the filtering? Can I specify the properties to look when I am doing an intersect?
Here is a sample code with example:
NSDictionary *dictionaryA1 = @{@"ID":@"1", @"Name":@"NameA1", @"Author":@"AuthorA1"};
NSDictionary *dictionaryA2 = @{@"ID":@"2", @"Name":@"NameA2", @"Author":@"AuthorA2"};
NSDictionary *dictionaryA3 = @{@"ID":@"3", @"Name":@"NameA3", @"Author":@"AuthorA3"};
NSDictionary *dictionaryB0 = @{@"bookID":@"0", @"Name":@"NameB0", @"Author":@"AuthorB0"};
NSDictionary *dictionaryB1 = @{@"bookID":@"1", @"Name":@"NameB1", @"Author":@"AuthorB1"};
NSDictionary *dictionaryB3 = @{@"bookID":@"3", @"Name":@"NameB3", @"Author":@"AuthorB3"};
NSArray *arrayA = @[dictionaryA1, dictionaryA2, dictionaryA3];
NSArray *arrayB = @[dictionaryB0, dictionaryB1, dictionaryB3];
NSArray *intersectionWithBookID = [arrayA filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ID IN %@", [arrayB valueForKey:@"bookID"]]];
NSLog(@"intersectionWithBookID: %@", intersectionWithBookID);
Output:
intersectionWithBookID: (
{
Author = AuthorA1;
ID = 1;
Name = NameA1;
},
{
Author = AuthorA3;
ID = 3;
Name = NameA3;
}
I m hopping your 2 NSArrays are like
arrayA = ( ObjectA1, ObjectA2, . . ObjectAn )
and
arrayB = ( ObjectB1, ObjectB2, . . ObjectBn )
In this case you have to first extract the values into separate arrays using predicate like this for both arrayA and arrayB
NSPredicate *predicateA = [NSPredicate predicateWithFormat:@"id"];
NSArray *arrayAWithonlyIds = [arrayA filteredArrayUsingPredicate:predicateA];
NSPredicate *predicateB = [NSPredicate predicateWithFormat:@"bookId"];
NSArray *arrayBWithonlyBookIds = [arrayA filteredArrayUsingPredicate:predicateB];
Now you have to convert these result array containing only ids to NSSet inorder to perform set operation like intersection like this
NSMutableset *setResult = [NSMutableSet setWithArray: arrayAWithonlyIds];
[setResult intersectSet:[NSSet setWithArray: arrayBWithonlyBookIds]];
I hope this gives you an Idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With