繁体   English   中英

核心数据 - 获取与数组中的值之一匹配的属性

[英]core data - fetch attribute that match one of the values in an array

我的核心数据模型:

Person 
======
personId  (NSNumber)

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

这就是我获取与一个 id 对应的人的方式:

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

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

为此使用“IN”匹配:

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

这是使用块创建您正在寻找的谓词的代码。

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

迅速

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM