SwiftUI发布的更新不刷新 [英] SwiftUI Published updates not refreshing
问题描述
我正在尝试通过一系列嵌套的类来管理用户状态.
I'm trying to manage user state via a series of nested classes.
应用程序的基本视图使用 globalState
环境对象.该对象允许用户向内和向外查看其他视图.
The basic view of the app uses a globalState
environment object. This object allows other views to the user in and out.
@EnvironmentObject var globalState: GlobalState
// View Code
Text("Logged In").opacity(globalState.user.isLoggedIn ? 1 : 0)
Text("Please Sign In").opacity(globalState.user.isLoggedIn ? 0 : 1)
然后, GlobalState
类仅容纳 User
类. user
字段在其他地方初始化(不,我没有引用其他 user
对象).
Then the GlobalState
class merely houses the User
class. The user
field is init'ed elsewhere (and no, I'm not referencing different user
objects).
class GlobalState: ObservableObject {
@Published public var user: User // Inited somewhere else
}
class User {
@Published var isLoggedIn: Bool = false
}
User
类在 init
初始化后自动提取有关用户的数据.在应用启动时,从钥匙串(如果有)中提取用户信息.如果可以从现有数据创建用户,则将该用户的 isLoggedIn
设置为 true
.
The User
class automatically pulls data about the user when it is init
ed. On app launch, user information is pulled from the Keychain (if present). If the user can be created from existing data, that user's isLoggedIn
is set to true
.
我知道我没有重复的对象,因为 globalState
的查看代码中 globalState.user
的内存地址与 isLoggedIn时的内存地址相同
已为用户更新.
I know I do not have duplicate objects, as the memory addresses of the globalState.user
in GlobalState
's View Code is the same as when isLoggedIn
is updated for a user.
通过使用两个级别的 @Published
变量,我对部队产生了干扰,但是一切应该解决吗?
I feel a disturbance in the Force by using two levels of @Published
variables, but everything should work out?
GlobalState
中的视图代码虽然不会更新.有人知道为什么吗?我缺少一些柔术柔术?
The view code in GlobalState
does not update though. Any one know why? Some Combine jiu jitsu I'm missing?
推荐答案
@Published
发布值更改,因此,如果要替换User对象,它将进行更新.由于User是类(引用类型),因此当User.isLoggedIn更改时,它将不会更新GlobalState.user的值.
@Published
publishes value changes, so if you would replace the User object it would update. Since User is a class (Reference type) it will not update the value of GlobalState.user when User.isLoggedIn changes.
此问题的解决方法是此名为NestedPublished的程序包,该程序包将嵌套的ObservableObject.willChange发送给其父级.
Fix for this is this package called NestedPublished which sends the nested ObservableObject.willChange to its parent.
这篇关于SwiftUI发布的更新不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!