【问题标题】:core data - fetch attribute that match one of the values in an array核心数据 - 获取与数组中的值之一匹配的属性
【发布时间】:2014-03-06 15:01:08
【问题描述】:

我的核心数据模型:

Person 
======
personId  (NSNumber)

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    为此使用“IN”匹配:

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

    【讨论】:

    • 至少 Swift 能做到这一点是好事。我习惯于使用原始 SQL 查询来提供真正的功能,但 Core Data 非常有限。
    【解决方案2】:

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

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

    【讨论】:

    • 请注意,基于块的谓词(以及一般基于 Objective-C 的谓词)不能与 Core Data 获取请求一起使用。
    【解决方案3】:

    斯威夫特

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

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2012-10-12
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多