🧩 iOS DiffableDataSource 死锁问题记录

本文提到的问题是实际项目中遇到的,但文章内容由ChatGPT完成,人工进行了review

🪪 错误信息

csharp 复制代码
Deadlock detected: calling this method on the main queue with outstanding async updates is not permitted and will deadlock. Please always submit updates either always on the main queue or always off the main queue

⚙️ 问题本质

在使用 UITableViewDiffableDataSource / UICollectionViewDiffableDataSource 时,

调用 apply(_:animatingDifferences:completion:) 方法更新数据。

  • 由于 apply() 本身是 异步执行 diff 计算与 UI 更新 的,如果在前一次 apply() 尚未完成时又调用了新的 apply(),UIKit 就会检测到潜在死锁并抛出上述错误。
  • "outstanding async updates" 表示仍在进行中的异步更新。 即上一次 diff 操作尚未完成,又发起了新的一次 diff

需要注意的是,虽然崩溃信息中提示是线程问题,但根据实际测试,即使所有调用都在主线程执行,也仍然可能发生此错误,因为 UIKit 内部的 diff 计算与视图更新是异步的。


🧭 解决思路

✅ 1. 防止重入(推荐)

使用标志位,确保同一时间只执行一次 apply(),并缓存后续请求:

swift 复制代码
private var isApplyingSnapshot = false
private var pendingSnapshot: NSDiffableDataSourceSnapshot<Section, Item>?

func applySnapshot(_ snapshot: NSDiffableDataSourceSnapshot<Section, Item>) {
    guard !isApplyingSnapshot else {
        pendingSnapshot = snapshot
        return
    }
    isApplyingSnapshot = true

    dataSource.apply(snapshot, animatingDifferences: true) { [weak self] in
        guard let self = self else { return }
        self.isApplyingSnapshot = false
        if let next = self.pendingSnapshot {
            self.pendingSnapshot = nil
            self.applySnapshot(next)
        }
    }
}

并可以根据该思想封装一个防止重入的类

swift 复制代码
import UIKit

/// 一个安全的 DiffableDataSource 快照更新管理器
/// 支持自动排队多次 apply,防止死锁与丢帧
final class SafeDiffableApplier<Section: Hashable, Item: Hashable> {
    private let dataSource: UITableViewDiffableDataSource<Section, Item>
    private var isApplying = false
    private var queue: [QueuedSnapshot] = []

    private struct QueuedSnapshot {
        let snapshot: NSDiffableDataSourceSnapshot<Section, Item>
        let animatingDifferences: Bool
        let completion: (() -> Void)?
    }

    init(dataSource: UITableViewDiffableDataSource<Section, Item>) {
        self.dataSource = dataSource
    }

    /// 安全地应用快照(自动排队,避免死锁)
    func apply(
        _ snapshot: NSDiffableDataSourceSnapshot<Section, Item>,
        animatingDifferences: Bool = true,
        completion: (() -> Void)? = nil
    ) {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            let task = QueuedSnapshot(snapshot: snapshot, animatingDifferences: animatingDifferences, completion: completion)
            self.queue.append(task)
            self.processNextIfNeeded()
        }
    }

    /// 按顺序依次执行队列中的快照更新
    private func processNextIfNeeded() {
        guard !isApplying, !queue.isEmpty else { return }
        isApplying = true

        let next = queue.removeFirst()
        dataSource.apply(next.snapshot, animatingDifferences: next.animatingDifferences) { [weak self] in
            guard let self = self else { return }
            next.completion?()
            self.isApplying = false
            self.processNextIfNeeded() // 递归继续下一个
        }
    }
}

✅ 2. 合并或节流更新

如果更新非常频繁,可以合并多次变化后再统一 apply()

swift 复制代码
func scheduleSnapshotUpdate() {
    pendingWorkItem?.cancel()
    let workItem = DispatchWorkItem { [weak self] in
        guard let self = self else { return }
        let snapshot = self.generateSnapshot()
        self.dataSource.apply(snapshot, animatingDifferences: true)
    }
    pendingWorkItem = workItem
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: workItem)
}

🧠 总结

  • apply()异步 的,不可重复调用。
  • 错误提示的 "outstanding async updates" 即代表上一次 diff 尚未完成。
  • 必须串行化更新操作,或合并多次更新。
  • 仅仅在主线程调度(DispatchQueue.main.async) 并不能根本解决问题。

参考


相关推荐
游戏开发爱好者81 天前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
黑码哥1 天前
ViewHolder设计模式深度剖析:iOS开发者掌握Android列表性能优化的实战指南
android·ios·性能优化·跨平台开发·viewholder
2501_915106321 天前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
熊猫钓鱼>_>1 天前
移动端开发技术选型报告:三足鼎立时代的开发者指南(2026年2月)
android·人工智能·ios·app·鸿蒙·cpu·移动端
徐同保2 天前
通过ip访问nginx的服务时,被第一个server重定向了,通过设置default_server解决这个问题
ios·iphone
2501_915918412 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_916007472 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
夏幻灵3 天前
HTTPS全面解析:原理、加密机制与证书体
ios·iphone
TheNextByte13 天前
如何在iPhone上恢复已删除的笔记的综合指南
笔记·ios·iphone