如何在视图外使用@Fetchrequest
How to use @Fetchrequest outside a View
我正在尝试将我的@fetchrequest 属性 移动到辅助 class,这不是 View
,但每次我尝试这样做时,我都会遇到问题指令错误。
谁能帮帮我?
这是我的代码示例:
视图模型:
class ViewModel {
@FetchRequest(entity: Teste.entity(), sortDescriptors: []) var teste: FetchedResults<Teste>
}
查看:
struct ContentView: View {
let viewModel: ViewModel
init(viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
List(viewModel.teste) { item in // error happens in this line
Text(item.id ?? "")
}
}
}
谢谢!
@FetchRequest
是 DynamicProperty
后者是
/// Represents a stored variable in a `View` type that is dynamically
/// updated from some external property of the view. These variables
/// will be given valid values immediately before `body()` is called.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicProperty {
因此,至少 "out of design" 尝试在 View
之外使用它。如果它真的是用例,那么直接在 UIKit+CoreData 中使用 NSFetchRequest
并手动将结果与 SwiftUI View 集成。
我在尝试自己弄清楚如何实现类似结果时遇到了您的问题。我猜你现在可能已经破解了这个问题,但是为了那些遇到同样问题的人的利益,我会尝试回答,或者至少指出可以找到答案的地方:-)
如前所述,@FetchRequest
属性 包装器在 View 组件之外不起作用(这似乎是一个奇怪的功能遗漏)
我发现的最佳替代方案是根据 Apostolos in his answer and detailed in a linked Medium post
的建议,通过 Combine
发布者实现与 NSFetchedResultsController
的更新基本上相同的事情
我整理了一个简单的概念验证示例,用于测试和演示 iOS14 的方法及其新的生命周期管理。这个演示应用程序可以在 here
我的 GitHub 仓库中找到
祝你好运。
我正在尝试将我的@fetchrequest 属性 移动到辅助 class,这不是 View
,但每次我尝试这样做时,我都会遇到问题指令错误。
谁能帮帮我?
这是我的代码示例:
视图模型:
class ViewModel {
@FetchRequest(entity: Teste.entity(), sortDescriptors: []) var teste: FetchedResults<Teste>
}
查看:
struct ContentView: View {
let viewModel: ViewModel
init(viewModel: ViewModel) {
self.viewModel = viewModel
}
var body: some View {
List(viewModel.teste) { item in // error happens in this line
Text(item.id ?? "")
}
}
}
谢谢!
@FetchRequest
是 DynamicProperty
后者是
/// Represents a stored variable in a `View` type that is dynamically /// updated from some external property of the view. These variables /// will be given valid values immediately before `body()` is called. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public protocol DynamicProperty {
因此,至少 "out of design" 尝试在 View
之外使用它。如果它真的是用例,那么直接在 UIKit+CoreData 中使用 NSFetchRequest
并手动将结果与 SwiftUI View 集成。
我在尝试自己弄清楚如何实现类似结果时遇到了您的问题。我猜你现在可能已经破解了这个问题,但是为了那些遇到同样问题的人的利益,我会尝试回答,或者至少指出可以找到答案的地方:-)
如前所述,@FetchRequest
属性 包装器在 View 组件之外不起作用(这似乎是一个奇怪的功能遗漏)
我发现的最佳替代方案是根据 Apostolos in his answer
Combine
发布者实现与 NSFetchedResultsController
的更新基本上相同的事情
我整理了一个简单的概念验证示例,用于测试和演示 iOS14 的方法及其新的生命周期管理。这个演示应用程序可以在 here
我的 GitHub 仓库中找到祝你好运。