SwiftUI:为什么 ObservedObject 在 AppDelegate 中不起作用? [英] SwiftUI: Why doesn't ObservedObject work in AppDelegate?

查看:28
本文介绍了SwiftUI:为什么 ObservedObject 在 AppDelegate 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过 ObservableObject 文档中的示例.>

I've tried the example from the ObservableObject documentation.

class Contact: ObservableObject {
    @Published var name: String = "me"
    @Published var age: Int = 7
}

当我用代码创建一个 Swift Playground 时:

When I make a Swift Playground with the code:

let c = Contact()
c.objectWillChange.sink { print("This prints") }
c.age += 1

objectWillChange 触发并打印行.

到目前为止一切顺利.

我现在在 SwiftUI 中创建一个视图:

I now make a View in SwiftUI:

struct ContentView: View {
    @ObservedObject var contact = Contact
    ...

我在 AppDelegate 中创建了这个视图,然后执行:

I create this View in the AppDelegate, and do:

   contentView.contact.objectWillChange.sink { print("This doesn't print.") }

我已将联系人连接到各种控件,更改任何字段都会更新所有控件.执行 onReceive(contact.objectWillChange) 也可以正常工作.但没有在 AppDelegate 中连接到它.我试过记录 deinit() 以确保我们谈论的是同一个对象.我试过使用 ImmediateScheduler.没有骰子.为什么这不起作用?

I've connected the contact to various controls, and changing any fields updates all the controls. Doing onReceive(contact.objectWillChange) also works fine. But not connecting to it in the AppDelegate. I've tried logging deinit() to make sure we're talking about the same object. I've tried using ImmediateScheduler. No dice. Why is this not working?

推荐答案

当您使用 .sink 创建订阅时,您必须保存返回的 AnyCancellable 对象

When you create a subscription with .sink you have to save the AnyCancellable object returned

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.

这篇关于SwiftUI:为什么 ObservedObject 在 AppDelegate 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆