更新核心数据对象Swift 3 [英] Update core data object swift 3

查看:78
本文介绍了更新核心数据对象Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在swift 3中更新核心数据对象.经过一番搜索,我没有找到关于swift 3的任何信息. 所以我的问题是:如何在Swift 3中更新核心数据对象?

I want to update a core data object in swift 3. After some googled I didn't found anything about swift 3. So my question is: how can I update a core data object in swift 3?

推荐答案

使用带有谓词的获取请求获取现有值.在谓词中使用唯一值.提取对象后,请使用新值更新对象并保存上下文.

Fetch the existing values using a fetch request with a predicate. Use a unique value in the predicate. Once you've fetched the object, update the object with new values and save the context.

let empId = "001"
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "EmpDetails")
let predicate = NSPredicate(format: "empId = '\(empId)'")
fetchRequest.predicate = predicate
do {
    let result = try persistentContainer.viewContext.fetch(fetchRequest)
    if let objectToUpdate = result.first as? NSManagedObject {
        objectToUpdate.setValue("newName", forKey: "name")
        objectToUpdate.setValue("newDepartment", forKey: "department")
        objectToUpdate.setValue("001", forKey: "empID")
        try persistentContainer.viewContext.save()
    }
} catch {
    print(error)
}

使用NSManagedObject子类

let empId = "001"
let fetchRequest: NSFetchRequest<Employee> = Employee.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "%K = %@", #keyPath(Employee.id), empId)
do {
  let results = try persistentContainer.viewContext.fetch(fetchRequest)
  if let employee = results.first {
    employee.name = "new name"
    employee.department = "new department"
  }
  try persistentContainer.viewContext.save()
} catch let error as NSError {
  print(error.localizedDescription)
}


批次更新

批处理更新有助于更新多个核心数据对象,而无需 将任何内容提取到内存中.


Batch updates

Batch updates help to update multiple Core Data objects without having to fetch anything into memory.

let batchUpdate = NSBatchUpdateRequest(entityName: "Employee")
batchUpdate.propertiesToUpdate = [#keyPath(Employee.isActive): true]
batchUpdate.affectedStores = persistentContainer.viewContext.persistentStoreCoordinator?.persistentStores
batchUpdate.resultType = .updatedObjectsCountResultType
do {
  let batchResult =  try coreDataStack.managedContext.execute(batchUpdate) as? NSBatchUpdateResult
  print(batchResult?.result)
} catch let error as NSError {
  print(error.localizedDescription)
}

这篇关于更新核心数据对象Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆