NSBatchUpdateRequest 在 Swift 中引发错误
Posted
技术标签:
【中文标题】NSBatchUpdateRequest 在 Swift 中引发错误【英文标题】:NSBatchUpdateRequest raise an error in Swift 【发布时间】:2015-09-07 14:16:54 【问题描述】:这是我的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
合作,所以我不知道以前是不是这样。对我来说,该代码应该可以正常工作。
【问题讨论】:
您找到解决方案了吗?我看到了完全相同的问题。 【参考方案1】:您必须刷新 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"
【讨论】:
【参考方案2】:我在项目中遇到的同样问题。下面的解决方案对我有用。试试这个
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 _
【讨论】:
以上是关于NSBatchUpdateRequest 在 Swift 中引发错误的主要内容,如果未能解决你的问题,请参考以下文章
NSFetchedResultsController 不知道数据已被 NSBatchUpdateRequest 更改