核心数据在存在时更新现有对象

时间:2017-01-10 13:43:24

标签: swift core-data

我创建了一个表:key,value。

这只是为了保存一些参数,当密钥不存在时,我会进行插入,但是当它存在时我会更新值。

在我的情况下,当密钥已经存在时,它在ma表中执行另一个插入,其键等于nil:

public static func insertValueWithKey(context: NSManagedObjectContext, key:String, value:String){

    let fetchRequest : NSFetchRequest<NSFetchRequestResult>

    if #available(iOS 10.0, *) {
        fetchRequest = Params.fetchRequest()
    } else {
        fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Params")
    }

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

    do {
        let results = try context.fetch(fetchRequest)

        if(results.count != 0){

            let paramsDescription = NSEntityDescription.entity(forEntityName: "Params", in: context)


            let params = NSManagedObject(entity: paramsDescription!, insertInto: context) as! Params


            params.value = value

            do {
                try context.save()
            } catch let error as NSError {
                print ("Error first demande insertion \(error)")
            }

        } else if (results.count == 0) {

            let params = NSEntityDescription.insertNewObject(forEntityName: "Params", into: context) as! Params

            params.key = key
            params.value = value

            context.insert(params)

            do {
                try context.save()
            } catch let error as NSError {
                print ("Error first demande insertion \(error)")
            }
        }


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

}

我不明白为什么,因为它在模拟器上运行良好,但在设备上却没有...

1 个答案:

答案 0 :(得分:1)

取代:

    let params = NSManagedObject(entity: paramsDescription!, insertInto: context) as! Params

    let params = results.last as! Params

NSManagedObject(entity: insertInto:)在功能上与NSEntityDescription.insertNewObject(forEntityName:into:)

相同