2015-07-09 36 views
0

我試圖用批量請求的幫助來更新swift中的單個實體。它適用於更新所有實體。是否有可能使用它的objectID更新單個實體? 以下是示例代碼:單個objectID的批量請求swift

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) 
} 

在此先感謝!

回答

0

不,不需要更新批量請求中的單個實體(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)