Question

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

Was it helpful?

Solution

Use 'IN' match for this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personId IN %@", idsArray];

OTHER TIPS

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
}];

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 []
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top