核心数据 - 与数组中的某个值匹配的fetch属性

时间:2014-03-06 15:01:08

标签: ios iphone objective-c core-data nsfetchrequest

我的核心数据模型:

Person 
======
personId  (NSNumber)

这是一个基本的核心数据问题,
我有一个personIds数组(不是Person,只是NSNumber个ID)我想要获取数组中具有相应id的所有Persons

这是我如何获取对应于一个id的人:

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

我正在寻找一种方法来获取与多个ID匹配的多个人

3 个答案:

答案 0 :(得分:13)

使用' IN'匹配这个:

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

答案 1 :(得分:0)

这是使用块创建谓词的代码。

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

答案 2 :(得分:0)

<强>夫特

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

完整示例:

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