当在SwiftUI列表中移动一行时,我注意到由于我的 "保存核心数据 "调用,UI过渡很卡顿。 我针对核心数据调用保存,因为列表项的orderNum已经改变,所以我改变了这一点。 下面是视频和代码。
代码 - 摘自我的SwiftUI视图
private var tasksFetchRequest : FetchRequest<GCTask>
private var gcTasks : FetchedResults<GCTask> { tasksFetchRequest.wrappedValue }
init(withGcList gcList:GCList) {
self.currentList = gcList
self.tasksFetchRequest = FetchRequest(
entity: GCTask.entity(),
sortDescriptors: [NSSortDescriptor(key: "orderNum", ascending: true)],
predicate: NSPredicate(format: "gcList == %@", currentList)
)
}
private func updateOrderNums(startIndex: Int, destIndex: Int, inc: Int) {
var currIndex = startIndex
while currIndex <= destIndex {
gcTasks[currIndex].orderNum = gcTasks[currIndex].orderNum + Int64(inc)
currIndex += 1
}
}
fileprivate func moveRow(fromStartIndex taskStartIndex: IndexSet.Element, toDestIndex taskDestIndex: Int, movingDown moveDown: Bool) {
gcTasks[taskStartIndex].orderNum = gcTasks[taskDestIndex].orderNum
updateOrderNums(
startIndex: moveDown ? taskStartIndex + 1 : taskDestIndex,
destIndex: moveDown ? taskDestIndex : taskStartIndex - 1,
inc: moveDown ? -1 : 1
)
// Save
GCCoreData.save() // <<== JERKINESS OCCURS DUE TO THIS
}
代码--库函数调用
class GCCoreData: NSObject {
static func save() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error performing Core Data save: \(nserror), \(nserror.userInfo)")
}
}
}
}