批量请求单个objectID swift



我试图在批量请求的帮助下在swift中更新单个实体。它可以完美地更新所有实体。是否有可能更新单一实体使用它的objectID?下面是示例代码:

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
 let managedContext = appDelegate.managedObjectContext    
 let batchRequest = NSBatchUpdateRequest(entityName: "Outlays")
 batchRequest.propertiesToUpdate = ["purchase": self.purchase.text!]
 batchRequest.resultType = .UpdatedObjectsCountResultType
 do {
   let results = try managedContext.executeRequest(batchRequest)  as! NSBatchUpdateResult
   print(" (results.result) results changed")
 } catch {
   print(error)
 }

提前感谢!

不需要在批处理请求中更新单个实体(NSManagedObject)。

最简单的方法就是在Outlays对象上设置新值。当然它们必须是NSManagedObject型的。之后在NSManagedObjectContext上调用saveContext:

myOutlay.text = "changed"
let managedContext = appDelegate.managedObjectContext 
var error: NSError? = nil
managedContext.save(&error)

如果您只有NSManagedObjectNSManagedObjectID,则需要首先从数据存储中获取它:

let managedContext = appDelegate.managedObjectContext 
var myOutlay: Outlays = managedObjectContext.existingObjectWithID(outlayManagedID, error: nil) as? Outlays
myOutlay.text = "changed"
let managedContext = appDelegate.managedObjectContext 
var error: NSError? = nil
managedContext.save(&error)

最新更新