Reputation: 2451
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
Upvotes: 5
Views: 4073
Reputation: 1904
Use 'IN' match for this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"personId IN %@", idsArray];
Upvotes: 14
Reputation: 11680
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 []
}
Upvotes: 0
Reputation: 2031
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
}];
Upvotes: 0