这是我的NSBatchUpdateRequest
:
let batchUpdateRequest = NSBatchUpdateRequest(entityName: "WLItem")
batchUpdateRequest.predicate = NSPredicate(format: "source != rt")
batchUpdateRequest.propertiesToUpdate = ["position": 2]
batchUpdateRequest.resultType = NSBatchUpdateRequestResultType.UpdatedObjectsCountResultType
do {
let batchUpdateResult = try NSManagedObjectContext.MR_defaultContext().executeRequest(batchUpdateRequest) as! NSBatchUpdateResult
} catch {
print("error: \(error)")
}
控制台上的输出是:
错误:NilError
有什么问题?这是XCode7的问题吗?我是第一次与NSBatchUpdateRequest
合作,所以我不知道之前是否是这样的。对我而言,代码应该可行。
答案 0 :(得分:2)
您必须刷新managedContextObject才能更新数据库。我创建了一个函数,其中使用NSBatchUpdateRequest来更新数据库。以下是功能: -
let managedContext = SharedInstance.appDelegate?.persistentContainer.viewContext
func updateDataFromTable(tableName:String, idOfPaticularTable ID:String, updatedDict:Dictionary<String, String>, success:@escaping (_ response:Bool)-> Void, failure:@escaping (_ error: Error?) -> Void) {
let batchRequest = NSBatchUpdateRequest(entityName: tableName)
let predicate = NSPredicate(format: "id == %@", ID)
batchRequest.predicate = predicate
batchRequest.propertiesToUpdate = updatedDict
batchRequest.resultType = .updatedObjectIDsResultType
do {
// Execute Batch Request
let batchUpdateResult = try managedContext?.execute(batchRequest) as! NSBatchUpdateResult
// Extract Object IDs
let objectIDs = batchUpdateResult.result as! [NSManagedObjectID]
for objectID in objectIDs {
// Turn Managed Objects into Faults
let managedObject = managedContext?.object(with: objectID)
managedContext?.refresh(managedObject!, mergeChanges: false)
}
success(true)
} catch let error as NSError {
print(error)
failure(error)
}
}
struct SharedInstance {
static let appDelegate = UIApplication.shared.delegate as? AppDelegate
static let employeetable = "EmployeeModel"
}
答案 1 :(得分:0)
我在项目中遇到的同样问题。以下解决方案为我工作。试试这个
let batchRequest = NSBatchUpdateRequest(entityName: "Card")
let predicate = NSPredicate(format: "set == %@", set)
batchRequest.predicate = predicate
batchRequest.propertiesToUpdate = [ "count" : 54 ]
batchRequest.resultType = .UpdatedObjectsCountResultType
do {
try self.managedObjectContext.executeRequest(batchRequest) as! NSBatchUpdateResult
} catch _ {
}