目前,我通过以下代码执行多次更新操作。
func updateOrders(_ updates : [(objectID: NSManagedObjectID, order: Int64)]) {
if updates.isEmpty {
return
}
let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext
backgroundContext.perform {
for update in updates {
let objectID = update.objectID
let order = update.order
let nsPlainNote = try! backgroundContext.existingObject(with: objectID) as! NSPlainNote
nsPlainNote.order = order
}
RepositoryUtils.saveContextIfPossible(backgroundContext)
}
}
既然我愿意
NSFetchedResultController
的代表收到通知我想利用
NSBatchUpdateRequest
来执行此类更新操作。
但是,我没有找到一种方法,如何将
NSManagedObjectID
数组和 Int64
值数组应用到 NSBatchUpdateRequest
。
给定一个
NSManagedObjectID
和Int64
的数组,是否可以使用NSBatchUpdateRequest
对CoreData执行更新?
您必须使用
NSPredicate
来设置对象id
func updateOrders(_ updates : [(objectID: NSManagedObjectID, order: Int64)]) {
updates.forEach {
let request = NSBatchUpdateRequest(entityName: "NSPlainNote")
request.propertiesToUpdate = ["order": $0.order]
request.predicate = NSPredicate(format: "objectID == %@", $0.objectID)
let result = try? context.execute(request)
}
}
NSBatchUpdateRequest
不适合您的任务,因为使用它对于具有公共属性值的大量记录有意义,以便您可以按您的条件过滤所有记录并立即使用您的值更新所有字段。
事实上,
NSBatchDeleteRequest
是一个NSPersistentStoreRequest
,它在持久存储本身的SQL级别上运行,并且在执行后不会更新内存中的对象,这就是为什么它运行得如此之快,并且Core Data可以翻译您对 SQL 的本机请求,您不能使用动态代码从字典等中获取和插入所需的数据,但您可以更新字段的当前值,例如:
let batchRequest = NSBatchUpdateRequest(entityName: "Note")
batchRequest.predicate = predicate
// Increase `order` value
batchRequest.propertiesToUpdate = ["order" : NSExpression(format: "order + 1")]
do {
try context.execute(batchRequest)
}
catch {
fatalError(error.localizedDescription)
}
NSBatchUpdateRequest:该类用于高效更新Core Data中的多条记录。
entityName:指定要更新的实体名称(在本例中为“Group”)。
predicate:定义一个条件来选择要更新的记录。在这里,它更新除 self.group 之外的所有实例。
propertiesToUpdate:要更新的属性及其新值的字典。
resultType:指定执行批量更新后想要接收的结果类型。
executeRequest:执行批量更新请求。
NSBatchUpdateResult:包含更新操作信息的结果对象。