1

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:

Arrays

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?

3 Answers 3

3

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

This approach is generally more suited to arrays / collections containing the same type of object
0
NSArray*            oldIds = [array2 valueForKeyPath:@"object1Id"];
NSPredicate*        predicate = [NSPredicate predicateWithFormat:@"NOT (id IN %@)", oldIds];
NSArray*            objects = [array1 filteredArrayUsingPredicate:predicate];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.