Check if name attribute already exists in CoreData

前端 未结 3 1443
忘掉有多难
忘掉有多难 2020-12-18 03:21

I have an entity called BankInfo, and one of its parameters is name which is a string. I\'m just wondering, is there a way in CoreData

3条回答
  •  醉话见心
    2020-12-18 03:35

    For Swift 5 use the below code, it similar to one of the upvoted answers, the only difference being use context.count instead of managedContext.count

                  let request : NSFetchRequest = 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)")
    

提交回复
热议问题