[英]SwiftUI: Why doesn't ObservedObject work in AppDelegate?
I've tried the example from theObservableObject documentation .我已经尝试过ObservableObject 文档中的示例。
class Contact: ObservableObject {
@Published var name: String = "me"
@Published var age: Int = 7
}
When I make a Swift Playground with the code:当我使用代码制作 Swift 游乐场时:
let c = Contact()
c.objectWillChange.sink { print("This prints") }
c.age += 1
objectWillChange
triggers and the line prints. objectWillChange
触发并打印行。
So far so good.到目前为止,一切都很好。
I now make a View in SwiftUI:我现在在 SwiftUI 中创建一个视图:
struct ContentView: View {
@ObservedObject var contact = Contact
...
I create this View in the AppDelegate, and do:我在 AppDelegate 中创建此视图,然后执行以下操作:
contentView.contact.objectWillChange.sink { print("This doesn't print.") }
I've connected the contact to various controls, and changing any fields updates all the controls.我已将联系人连接到各种控件,更改任何字段都会更新所有控件。 Doing
onReceive(contact.objectWillChange)
also works fine.执行
onReceive(contact.objectWillChange)
也可以。 But not connecting to it in the AppDelegate.但没有在 AppDelegate 中连接到它。 I've tried logging
deinit()
to make sure we're talking about the same object.我尝试记录
deinit()
以确保我们谈论的是相同的 object。 I've tried using ImmediateScheduler
.我试过使用
ImmediateScheduler
。 No dice.没有骰子。 Why is this not working?
为什么这不起作用?
When you create a subscription with .sink
you have to save the AnyCancellable
object returned当您使用
.sink
创建订阅时,您必须保存返回的AnyCancellable
object
let cancellable = publisher.sink { ... }
And if you assign it to a variable, make sure it is not short lived.如果将其分配给变量,请确保它不是短暂的。 As soon as the cancellable object gets deallocated, the subscription will get cancelled too.
一旦可取消的 object 被解除分配,订阅也将被取消。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.