I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject
with a parameter coming from an initializer.
To be more specific, this snippet of code works fine:
struct MyView: View {
@StateObject var myObject = MyObject(id: 1)
}
But this does not:
struct MyView: View {
@StateObject var myObject: MyObject
init(id: Int) {
self.myObject = MyObject(id: id)
}
}
From what I understand the role of @StateObject
is to make the view the owner of the object.
The current workaround I use is to pass the already initialized MyObject instance like this:
struct MyView: View {
@ObservedObject var myObject: MyObject
init(myObject: MyObject) {
self.myObject = myObject
}
}
But now, as far as I understand, the view that created the object owns it, while this view does not.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…