gpt4 book ai didi

ios - NSBatchUpdateRequest 在 Swift 中引发错误

转载 作者:可可西里 更新时间:2023-11-01 01:39:02 25 4
gpt4 key购买 nike

这是我的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)")
}

控制台输出为:

error: NilError

怎么了? XCode7有问题吗?我是第一次使用 NSBatchUpdateRequest,所以我不知道以前是不是这样。对我来说,该代码应该可以正常工作。

最佳答案

您必须刷新 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"
}

关于ios - NSBatchUpdateRequest 在 Swift 中引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32440803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com