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

3 Answers 3

14

Use 'IN' match for this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personId IN %@", idsArray];
1
  • 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
    Commented Jun 1, 2016 at 4: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
}];
1
  • Note that block-based predicates (and Objective-C based predicates in general) cannot be used with a Core Data fetch request.
    – Martin R
    Commented Mar 6, 2014 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 []
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.