更新核心数据swift 4上的对象

时间:2018-02-12 06:01:27

标签: ios swift core-data objectid

我在核心数据实体中有几项作业,其jobId为-1。我需要获取所有这些项目并通过在updateMyJobs方法中传递的对象中的适当ID更新jobId。我没有提取NSManagedObject类来处理核心数据(即 - 我已将实体检查为类定义)

这是我的代码:

func updateMyJobs(jobId: Int){
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DBJobsNearBy")
    fetchRequest.predicate = NSPredicate(format: "jobId = '-1'")
    let result = try? managedObjectContext.fetch(fetchRequest)
    let resultData = result as! [DBJobsNearBy]
    for object in resultData {
        print(object.jobId)
        if object.jobId == -1 {
            object.setValue("\(jobId)", forKey: "jobId")
        }
    }
    do {
        try managedObjectContext.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
}

我传递了一些整数值并调用上面的方法来更新这样的项目。

DatabaseHandler.shared.updateMyJobs(jobId: 222)

错误:因未捕获的异常终止应用&#39; NSInvalidArgumentException&#39;,原因:&#39;属性的值不可接受的类型:property =&#34; jobId&#34 ;;所需类型= NSNumber;给定type = Swift._NSContiguousString;值= 222。&#39;

我试图将新jobId设置为核心数据实体中的相关对象。是否有必要提取NSManagedObject类。请有人帮我这样做。谢谢。

3 个答案:

答案 0 :(得分:4)

请阅读错误消息。很清楚。在setValue中,您传递的是String(通过字符串插值),而不是预期的IntNSNumber

object.setValue(jobId, forKey: "jobId")

object.setValue(NSNumber(value: jobId), forKey: "jobId")

但最佳和推荐的方式是点符号

object.jobId = jobId

答案 1 :(得分:0)

您需要设置NSNumber而不是String。替换此行:

object.setValue("\(jobId)", forKey: "jobId")

使用:

object.jobId = jobId

答案 2 :(得分:0)

将对象更新为核心数据

@IBAction func buttonUpdate(_ sender: Any) {
        let entity = NSEntityDescription.entity(forEntityName: "Students", in: managedContext)
        let request = NSFetchRequest<NSFetchRequestResult>()
        request.entity = entity
        let newName = UserDefaults.standard.value(forKey: "new") as! String
        let predicate = NSPredicate(format: "(name = %@)", newName)
        request.predicate = predicate
        do {
            let results =
                try managedContext.fetch(request)
            let objectUpdate = results[0] as! NSManagedObject
            objectUpdate.setValue(txtName.text!, forKey: "name")
            objectUpdate.setValue(txtPhone.text!, forKey: "phone")
            objectUpdate.setValue(txt_Address.text!, forKey: "address")
            do {
                try managedContext.save()
                labelStatus.text = "Updated"
            }catch let error as NSError {
              labelStatus.text = error.localizedFailureReason
            }
        }
        catch let error as NSError {
            labelStatus.text = error.localizedFailureReason
        }

    }