Reputation: 12942
I've got 2 arrays:
array1
contains objects of type object1
. object1
has a property id
.
array2
contains objects of type object2
. object2
has a property object1Id
.
I know, that array2
contains objects with ids which always are in array1
, but array1
can have more (or equal) objects.
To show it:
So to simplify: array1
has all objects, array2
has new objects. How to get an array with old objects..? I'm trying to do it with predicate, but it feels odd to do a loop and insert each object1Id
to the predicate. Is there any other option? How to do it properly?
Upvotes: 1
Views: 155
Reputation: 41226
NSArray* oldIds = [array2 valueForKeyPath:@"object1Id"];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"NOT (id IN %@)", oldIds];
NSArray* objects = [array1 filteredArrayUsingPredicate:predicate];
Upvotes: 0
Reputation: 40030
It looks like you are trying to perform a set operations. What can be helpful is NSMutableSet
class. Use setWithArray
to create sets. Then use methods like:
unionSet:
minusSet:
intersectSet:
setSet:
To get subsets that match your criteria.
Source: NSMutableSet Class Reference
Hope it helps.
Upvotes: 1
Reputation: 119021
You can use a predicate, and you don't need a loop if you use KVC.
Get the array of ids that should be excluded:
NSArray *excludeIds = [array2 valueForKey@"object1Id"];
Create the predicate:
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (id IN %@)", excludeIds];
Then filter:
NSArray *oldObjects = [array1 filteredArrayUsingPredicate:filterPredicate];
Upvotes: 3