5

My core data model:

Person 
======
personId  (NSNumber)

This is a basic core data question,
I have an array of personIds (not Person, just NSNumber of ids) and I want to fetch all the Persons with corresponding id in the array.

This is how I fetch a person that correspond to one id:

   NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
   request.predicate = [NSPredicate predicateWithFormat:@"personId = %@", onePersonId];

I'm looking for a way to fetch multiple persons that match to multiple ids

Mario
  • 2,431
  • 6
  • 27
  • 34

3 Answers3

14

Use 'IN' match for this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personId IN %@", idsArray];
Cliff Ribaudo
  • 8,932
  • 2
  • 55
  • 78
ksh
  • 1,894
  • 19
  • 20
  • Its good that Swift can do this much at least. I am used to raw SQL queries which give the real power, but Core Data is very limiting. – zeeshan Jun 01 '16 at 04:27
0

Here is code which creates predicate which you are looking for using block.

NSPredicate *predicate= [NSPredicate predicateWithBlock:^BOOL(Person *person, NSDictionary *bind){
    return [arrayOfIds containsObject:person.personId]; //check whether person id is contained within your array of IDs
}];
Rafał Augustyniak
  • 2,011
  • 19
  • 14
  • Note that block-based predicates (and Objective-C based predicates in general) cannot be used with a Core Data fetch request. – Martin R Mar 06 '14 at 18:21
0

Swift

let ids: [NSNumber] = [1234, 5678]
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "YourEntityName")
fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)

Full Example:

func getAllThings(withIds ids: [NSNumber]) -> [Thing] {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Thing")
    fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)

    do {
        if let things = try context.fetch(fetchRequest) as? [Thing] {
            return things
        }
    } catch let error as NSError {
        // handle error
    }

    return []
}
Derek Soike
  • 11,238
  • 3
  • 79
  • 74