【问题标题】:Using SwiftUI with Core Data将 SwiftUI 与核心数据一起使用
【发布时间】:2019-10-28 15:09:11
【问题描述】:

SwiftUI 表需要绑定到在内存中存储整个模型对象的数组。对于小型数据集,便利性与性能的权衡是有意义的。但是对于具有数万/数十万个值的数据集,通过查询数据源来呈现表的老式方法似乎仍然是可行的方法。 (考虑一个简单的字典/词库应用程序。)。

有没有办法在 SwiftUI 中实现 dataSource 样式/CoreData 支持的表?

【问题讨论】:

  • 由于没有评论,我只能假设我下面的答案由于某种原因不合适,所以我删除了它。如果您仍在寻找有关如何在 SwiftUI 中使用 CoreData 的一些提示和技巧,并且需要一个开始的地方,请查看我对 *.com/questions/57348127/… 的回答

标签: core-data swiftui


【解决方案1】:

列表不需要ArrayData 必须符合 RandomAccessCollection 协议。 这也可能是您的NSFetchedResultsController

extension List {
    /// Creates a List that computes its rows on demand from an underlying
    /// collection of identified data.
    @available(watchOS, unavailable)
    public init<Data, RowContent>(
        _: Data,
        selection _: Binding<Selection>?,
        rowContent _: @escaping (Data.Element.IdentifiedValue) -> RowContent
    ) where Content == ForEach<Data, HStack<RowContent>>,
        Data: RandomAccessCollection,
        RowContent: View,
        Data.Element:
        Identifiable

    /// Creates a List that computes its rows on demand from an underlying
    /// collection of identified data.
    @available(watchOS, unavailable)
    public init<Data, RowContent>(
        _: Data,
        selection _: Binding<Selection>?,
        action _: @escaping (Data.Element.IdentifiedValue) -> Void,
        rowContent _: @escaping (Data.Element.IdentifiedValue) -> RowContent
    ) where Content == ForEach<Data, Button<HStack<RowContent>>>,
        Data: RandomAccessCollection,
        RowContent: View, Dat
}

【讨论】:

  • 你好 Ugo,我不明白你发布的代码有什么帮助?下一步是什么?
【解决方案2】:

我认为这就是在 SwiftUI 中使用 ForEach() 循环的原因,因此视图可以控制需要实例化多少元素才能填满屏幕。

Core Data fetch 请求中的 Array 可能并不包含内存中的所有对象,它们仅在被访问时才会被实例化。

【讨论】:

    最近更新 更多