SwiftUI列表在移动行时 "卡顿",由Core Data保存触发更新orderNum。

问题描述 投票:0回答:1

当在SwiftUI列表中移动一行时,我注意到由于我的 "保存核心数据 "调用,UI过渡很卡顿。 我针对核心数据调用保存,因为列表项的orderNum已经改变,所以我改变了这一点。 下面是视频和代码。

enter image description here

代码 - 摘自我的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)")
            }
        }
    }

}
core-data swiftui swiftui-list
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.