美文网首页
(WWDC) UI 数据源的进步

(WWDC) UI 数据源的进步

作者: FicowShen | 来源:发表于2019-07-14 18:22 被阅读0次

    内容概览

    • 现状
    • 新方法
    • Demos
    • 注意事项



    现状

    实现 UICollectionViewDataSource 协议中的方法

    UICollectionViewDataSource 简单、灵活,但这也致使应用变得复杂。
    使用 UICollectionViewDataSource 时,通常需要 Controller 来维护 UI 数据。

    更新 UI 可能会遭遇一些问题,比如:

    *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
    reason: 'Invalid update: invalid number of sections. The number of sections contained in the 
    collection view after the update (10) must be equal to the number of sections contained in the 
    collection view before the update (10), plus or minus the number of sections inserted or
    deleted (0 inserted, 1 deleted).'
    ***
    

    问题的根源在于:

    • 数据源和当前 UI 状态必须总是保持一致
    • 目前的方法容易导致错误
    • 没有集中的事实



    新方法

    Diffable Data Source

    performBatchUpdates() 方法复杂、繁琐而且易导致崩溃
    apply() 方法简单而且可以自动辨别更新

    Snapshot

    • UI 状态的事实
    • Section 和 Item 都有唯一的 ID
    • 不再需要依赖 IndexPath
    当前快照 将新快照应用到旧快照上 最终的快照

    苹果提供的相关类型:

    // 集中的数据源
    UICollectionViewDiffableDataSource
    UITableViewDiffableDataSource
    NSCollectionViewDiffableDataSource
    
    // 数据源快照
    NSDiffableDataSourceSnapshot
    



    Demos

    点击下载 官方 Demo

    下载后,解压。然后使用 Xcode 11 打开。

    只需要关注 Diffable 部分



    注意事项

    更新数据源时:

    • 总是使用数据源的 apply() 方法
    • 不再使用 performBatchUpdates(), insertItems() 等方法

    构建快照时:

    • 空快照
    • 当前数据源的快照
    获取快照的状态 配置快照

    标识符需要满足以下条件:

    • 必须唯一
    • 遵守 Hashable 协议
    • 使用数据模型或者对象的 ID
    自定义标识符 示例

    如何使用基于 IndexPath 的 API?

    关于 apply() 方法:

    • 非常高效,时间复杂度为 O(1)
    • 允许在后台线程执行

    需要注意的是,一旦选择在后台线程执行 apply() 方法,就不能再切换到主线程执行。
    如果有错误发生,系统会对错误进行记录,或者用 assert 中断执行。

    最后,强烈建议使用新方法:

    • 支持 iOS, tvOS 和 macOS
    • 自动配置动画
    • 易用、高效而且稳健




    参考内容:
    Advances in UI Data Sources




    转载请注明出处,谢谢~

    相关文章

      网友评论

          本文标题:(WWDC) UI 数据源的进步

          本文链接:https://www.haomeiwen.com/subject/fyomkctx.html