使用NSPredicate将对象保存到核心数据

时间:2015-10-31 21:49:55

标签: ios swift core-data parse-platform

我正在尝试将对象保存到从Parse获取的Core Data,但我只想要那些不包含已存在于数据库中的名称的对象:

func fetchFromParse() {

    let entity = NSEntityDescription.entityForName("Medicine", inManagedObjectContext: context)
    let query = PFQuery(className: "Medicine")
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            for object in objects! {
                let medicine = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: self.context)

                if let  name = object["medicineName"] as? String,
                    amount = object["amountQuantity"] as? String {

                        let predicate = NSPredicate(format: "name != %@", name)
                        self.fetchRequest.predicate = predicate

                        do{
                            let fetchedEntities = try self.context.executeFetchRequest(self.fetchRequest) as! [Medicine]
                            //save to  Core Data


                            medicine.setValue(name, forKey: "name")
                            medicine.setValue(amount, forKey: "amount")

                        } catch let error as NSError{
                            print(error)
                        }

                        do {
                            try self.context.save()
                            self.tableView.reloadData()
                        } catch let error as NSError {
                            print("Could not save \(error), \(error.userInfo)")
                        }
                }
            }
        }
    }
}

从核心数据中获取数据

func fetchFromCoreData() {

    do {
        let results = try context.executeFetchRequest(fetchRequest)
        medicines = results  as! [Medicine]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }


}

我把它放在viewWillAppear:

if Reachability.isConnectedToNetwork() {
        //fetching data from Parse

        fetchFromParse()
        fetchFromCoreData()
        tableView.reloadData()

    } else {
        //fetching data from Core data
        fetchFromCoreData()
        logOutButton.enabled = false

    }

但它不起作用。有任何建议如何修复它?

1 个答案:

答案 0 :(得分:0)

你有一切,只是没有联系。在您执行并检查获取之前,您不应该实例化并插入新对象。您当前正在执行提取但不检查是否存在重复。这两个问题都需要解决,这有点像:

let entity = NSEntityDescription.entityForName("Medicine", inManagedObjectContext: context)
let query = PFQuery(className: "Medicine")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
    if error == nil {
        for object in objects! {

            if let  name = object["medicineName"] as? String,
                amount = object["amountQuantity"] as? String {

                    let predicate = NSPredicate(format: "name = %@", name)
                    self.fetchRequest.predicate = predicate

                    do{
                        let fetchedEntities = try self.context.executeFetchRequest(self.fetchRequest) as! [Medicine]
                        //save to  Core Data

                        if fetchedEntities.count <= 0 {
                            let medicine = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: self.context)
                            medicine.setValue(name, forKey: "name")
                            medicine.setValue(amount, forKey: "amount")
                        }
                    } catch let error as NSError{
                        print(error)
                    }
            }
        }

         do {
              try self.context.save()
         } catch let error as NSError {
              print("Could not save \(error), \(error.userInfo)")
         }
    }
}