ios - NSFetchedResultsController 使加载 View Controller 非常慢

标签 ios swift performance core-data nsfetchedresultscontroller

(更新:在下面的编辑 4 中,我确实找到了问题的原因!)

我正在使用带有 NSFetchedResultsControllertableView。这就是我获取数据的方式(我在 viewDidLoad() 中调用它):

let fetchRequest: NSFetchRequest<Entry> = Entry.fetchRequest()
        let sortSections = NSSortDescriptor(key: #keyPath(Entry.section), ascending: false)
        let sortDate = NSSortDescriptor(key: #keyPath(Entry.date), ascending: true)
        fetchRequest.sortDescriptors = [sortSections, sortDate]
        fetchRequest.fetchBatchSize = 15 // this seems to have no impact
        fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObject, sectionNameKeyPath: #keyPath(Entry.section), cacheName: "EntriesCache")

不知何故,这非常慢(当我转到包含此 table viewview controller 时,我注意到了这一点)。

在我的设备上,我对数据库中的大约 200 个 Entry 对象进行了尝试。 view controller 的显示时间略多于 1 秒。但我也尝试了大约 10 个对象,它并没有那么快。 (奇怪的是,在模拟器上它的速度非常快)

我尝试使用 Time Profiler 对其进行分析。在这 1 秒内,CPU 处于 100%。这正常吗?

在我注意到这种缓慢的性能之前,我没有这条线

fetchRequest.fetchBatchSize = 15

我添加了它但没有任何改变。它甚至没有一点点快。我还打印了加载后获取的对象的数量:

print(fetchedResultsController.fetchedObjects?.count)

它表示所有对象都已加载,而不仅仅是其中的 15 个(因为在 TableView 中您不能一次看到更多)。这是为什么?

这是我用于 TableView 条目实体 Entry Entity

我不知道您需要什么代码/信息才能帮助我(我不是性能问题方面的专家)。如果您还需要其他任何东西,请告诉我。

谢谢你们!

编辑:

我如何访问 managedObjectContext:

lazy var managedObject: NSManagedObjectContext = {
        let managedObject = self.appDelegate.persistentContainer.viewContext
        return managedObject
    }()

编辑 2(也许我找到了原因?): 好的,所以我编辑了我的方案,以便它向我显示所有 SQL 查询。首先,它多次加载 15 行(当 15 是 fetchBatchSize 时)。但在那之后它变得有趣:

我没有准确计算它,但我很确定它对数据库中的每个对象 执行以下查询。我用 600 个左右的对象进行了尝试,运行这些 SQL 查询需要很长时间:

CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, Z_FOK_ENTRY FROM ZENTRYTEXT t0 WHERE  t0.ZENTRY = ? 
CoreData: annotation: sql connection fetch time: 0.0001s
CoreData: annotation: total fetch execution time: 0.0002s for 1 rows.
CoreData: annotation: to-many relationship fault "entryTexts" for objectID 0xd000000006480000 <x-coredata://C53DABDD-5D31-4ADE-B6E7-3ED69454B572/Entry/p402> fulfilled from database.  Got 1 rows
CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZTEXT, t0.ZENTRY, t0.Z_FOK_ENTRY FROM ZENTRYTEXT t0 WHERE  t0.Z_PK = ? 
CoreData: annotation: sql connection fetch time: 0.0001s
CoreData: annotation: total fetch execution time: 0.0002s for 1 rows.
CoreData: annotation: fault fulfilled from database for : 0xd000000007940002 <x-coredata://C53DABDD-5D31-4ADE-B6E7-3ED69454B572/EntryText/p485>

我不知道那到底是什么,但我认为它导致了延迟。这些查询运行完毕后,将显示 View Controller 。

编辑 3:

这是我的 TableView 数据源方法:

func numberOfSections(in tableView: UITableView) -> Int {
        guard let sections = fetchedResultsController.sections else {
            return 0
        }
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        
        guard let sectionInfo = fetchedResultsController.sections?[section] else {
            return 0
        }

        return sectionInfo.numberOfObjects
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "bitCell") as! BitCell
        let entry = fetchedResultsController.object(at: indexPath)

        cell.configure(entry: entry)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let entry = fetchedResultsController.object(at: indexPath)
        extendBitPopup.fadeIn(withEntry: entry, completion: nil)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y >= 400 {
            UIView.animate(withDuration: 0.5, animations: { 
                self.arrowUpButton.alpha = 1.0
                self.arrowUpButton.isEnabled = true
                self.arrowUpButton.isUserInteractionEnabled = true
            })
        } else {
            UIView.animate(withDuration: 0.5, animations: {
                self.arrowUpButton.alpha = 0.0
                self.arrowUpButton.isEnabled = false
                self.arrowUpButton.isUserInteractionEnabled = false
            })
        }
    }


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let entry = fetchedResultsController.object(at: indexPath)
        guard !entry.isFault else {
            return 0
        }
        // this estimates the height the cell needs when the text is inserted
        return BitCell.suggestedHeight(forEntry: entry)
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if let sectionInfo = fetchedResultsController.sections?[section] {
            let dateFormatter = DateFormatter()
            // Entry.section has this format: "yyyyMMdd" I chose this to make a section for each day. 
            dateFormatter.dateFormat = "yyyyMMdd"
            let date = dateFormatter.date(from: sectionInfo.name)!

            dateFormatter.dateStyle = .full
            dateFormatter.timeStyle = .none

            return dateFormatter.string(from: date)
        }

        return ""

    }


    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }


    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 25
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let moment = UITableViewRowAction(style: .normal, title: "Moment") { (action, indexPath) in
            let entry = self.fetchedResultsController.object(at: indexPath)
            entry.isMoment = !entry.isMoment
            self.appDelegate.saveContext()
            tableView.setEditing(false, animated: true)
        }
        moment.backgroundColor = AppTheme.baseGray

        let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, index) in
            let entry = self.fetchedResultsController.object(at: indexPath)
            self.managedObject.delete(entry)
            self.appDelegate.saveContext()
            tableView.setEditing(false, animated: true)
        }
        delete.backgroundColor = AppTheme.errorColor

        return [delete, moment]
    }

编辑4(找到原因):

问题是这个函数:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let entry = fetchedResultsController.object(at: indexPath)
        guard !entry.isFault else {
            return 0
        }
        return BitCell.suggestedHeight(forEntry: entry)
    }

我试过这个,现在我几乎可以肯定这条线是麻烦制造者:

let entry = fetchedResultsController.object(at: indexPath)

如果我在这一行之前返回静态 CGFloat, View Controller 几乎会立即加载(我用 700 个对象对其进行了测试)。此外,它随后仅获取前 50 个项目(即 fetchBatchSize),并且仅在您向下滚动时加载更多项目。

如果我在这一行之后返回,它会获取所有数据(根据许多 SQL 查询),它会变得非常慢,并且会出现整个延迟问题。

所以,我认为如果上面的这一行试图获取一个错误的对象(也许它然后试图从数据库或其他东西重新获取),就会出现问题

现在的问题是:如何解决这个问题?我需要 Entry 对象来估计单元格高度,但我只想在我知道该对象没有故障(如果这是问题所在)时调用此行。我该怎么做?

最佳答案

使用估计高度委托(delegate)方法,并返回固定尺寸。 TableView 应该只在需要显示该行时查询该行的实际高度,这样它才能正确使用获取结果 Controller 的错误和批处理功能。

如果一个表有 400 行,并且您已经实现了 heightForRow,那么它将为表中的每一行调用委托(delegate)方法,以便它可以计算 TableView 的内容大小。向结果 Controller 询问某个索引处的对象会自动将其从故障中转换,并且在任何情况下返回零大小都会完全弄乱您的表的内容大小。

如果您改为提供估计大小,通过使用委托(delegate)方法或将其设置为表格的属性,则表格 View 将只为显示或即将显示的行调用特定的高度方法.它将使用估计的高度来猜测 TableView 的内容大小。这意味着当您滚动时内容大小会略有波动,但这并不是很明显。

关于ios - NSFetchedResultsController 使加载 View Controller 非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836639/

相关文章:

ios - swift: UITextField 没有名为 text 的成员

iphone - 比较两个无符号字符缓冲区

Swift:符合协议(protocol)中的属性?

ios - 在 NSCache 中存储结构的任何方式

ios - 在 Swift 中实现惰性属性并将其设置为 nil

linux - 测量内核空间开销的准确方法

ios - 像 UIView 这样的 Twitter 上的建议

ios - 高效处理多次/频繁调用 UIView needsDisplayInRect

c - 使用 OpenMP 和 PThreads 的并行程序比顺序程序慢

c - 试图理解 gcc 选项 -fomit-frame-pointer