【问题标题】:How to get CoreData attributes from a ViewController swift如何从 ViewController swift 中获取 CoreData 属性
【发布时间】:2020-09-05 13:03:09
【问题描述】:

我有一个简单的 CoreData 堆栈,其中包含一个 CoreData 类 Booking,我想在 ViewController 中使用它。我想获取Booking 的每条记录,并使用每个记录中的data 属性将事件放入日历视图控制器中。

我发现这段代码应该获取 CoreData 实体,它似乎没问题 - 我只是不知道如何在此之后使用这些数据,例如在循环中获取 Booking.date 属性并打印它.

我的ViewController 课堂上有这个:

    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(
        entity: Booking.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Booking.id, ascending: false)
        ]
    ) var bookings: FetchedResults<Booking>

这没有错误,但是我不能确定这实际上是从Booking 实体获取数据,因为我不知道如何使用它返回的任何内容。

我尝试在我的override func loadView() 方法中使用print(bookings)。它在打印语句时崩溃,似乎是因为它是 nil 并且没有打开 - 但是当我尝试打开它时没有任何效果。

我认为我从 CoreData 获取 Bookings 的方式一定有问题,但我就是不知道这是什么问题。有没有特定的方法可以从ViewController访问这些数据

请注意,我在AppDelegate 中为NSPersistantContainersaveContext 完成了所有必要的设置。我已经设法在我的代码的其他区域使用CoreData,所以我知道它的这方面工作正常。 ViewController 让我很困惑

【问题讨论】:

  • 如果你真的使用 ViewController 类,那么这些属性包装器都不能正常工作(如果能正常工作的话),因为它们只是为 SwiftUI 视图设计的。
  • 这是有道理的。我想我没有意识到这一点。感谢您的信息。

标签: ios swift core-data swiftui


【解决方案1】:

FetchedResultsController 放入用作您的 Manager/ViewModel 的 ObservableObject 会有所帮助。

https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller

@Published var bookings 将通过NSFetchedResultsControllerDelegate 的方法controllerDidChangeContent(_:) 更新

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/nsfetchedresultscontroller.html

通过单例模式或其他模式使用ObservableObject 的共享实例将使您能够在ViewController 和SwiftUI View 之间共享数据。

我不久前为另一个问题制作了这个视频,该视频显示了基本设置。的FetchedResultsController https://www.youtube.com/watch?v=-U-4Zon6dbE

【讨论】:

  • 对于我的日历组件,我使用UIViewController 类。我可以在其中使用ObservableObject 吗?我还使用 UIViewControllerRepresentable 在 SwiftUI 堆栈中显示它。如果 Observable Object 仅用于 SwiftUI,我不确定如何将 CoreData 实体放入我的 UIViewController 类中。
  • @ObservedObject 只能在 SwiftUI 中用于更新 UIViewController,您将在传统意义上使用 FetchedResultsController(在第二个链接中描述。controllerDidChangeContent(_:) 更新了 @987654340 @ 和你的 UIViewController
猜你喜欢
  • 2018-03-25
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 2017-06-13
相关资源
最近更新 更多