检查CoreData中是否已存在name属性

时间:2013-12-27 04:31:17

标签: ios iphone cocoa-touch core-data

我有一个名为BankInfo的实体,其中一个参数是name,这是一个字符串。我只是想知道,CoreData中是否有办法检查并name中是否已存在BankInfo而无需检索每个BankInfo对象并循环浏览它们单独检查?实现这一目标的最有效方法是什么?

3 个答案:

答案 0 :(得分:22)

您可以使用获取请求谓词来查找与特定属性匹配的对象。 如果您只对存在感兴趣 使用给定键的对象,使用countForFetchRequest而不是实际获取对象,并将结果集限制为一个对象:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"BankInfo"];
[request setPredicate:[NSPredicate predicateWithFormat:@"name = %@", theName]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound)
    // some error occurred
else if (count == 0)
    // no matching object
else
    // at least one matching object exists

答案 1 :(得分:11)

对于其他喜欢我的人来说,最终在这里寻找 Swift 3 解决方案,这里是:

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "BankInfo")
let predicate = NSPredicate(format: "name == %@", theName)
request.predicate = predicate
request.fetchLimit = 1

do{
    let count = try managedContext.count(for: request)   
    if(count == 0){
    // no matching object
    }
    else{
    // at least one matching object exists
    }
  }
catch let error as NSError {
     print("Could not fetch \(error), \(error.userInfo)")
  }

答案 2 :(得分:0)

对于 Swift 5 ,请使用下面的代码,它与最新的答案之一相似,唯一的区别是使用context.count而不是managedContext.count

              let request : NSFetchRequest<MachineTypeTolerance> = MachineTypeTolerance.fetchRequest()
            let predicate = NSPredicate(format: "machineType = %@", type)
            request.predicate = predicate
            request.fetchLimit = 1

            do{
                let count = try context.count(for: request) 
//instead of managedContext use context, where let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
                if(count == 0){
                print("no matches")
                }
                else{
                print("match found")
                }
              }
            catch let error as NSError {
                 print("Could not fetch \(error), \(error.userInfo)")