问题
I am trying to move my @fetchrequest property to an auxiliar class, which is not a View
, but every time I try to do that, I get a bad instruction error.
Can anyone help me?
This is a sample of my code:
ViewModel:
class ViewModel {
@FetchRequest(entity: Teste.entity(), sortDescriptors: []) var teste: FetchedResults<Teste>
}
View:
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 ?? "")
}
}
}
Thank you!
回答1:
@FetchRequest
is a DynamicProperty
and latter is
/// 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 {
So it is, at least, "out of design" to try to use it outside of View
. If it is really use-case then use NSFetchRequest
directly as previously in UIKit+CoreData and integrate results with SwiftUI View manually.
来源:https://stackoverflow.com/questions/60101859/how-to-use-fetchrequest-outside-a-view