有一种更复杂的观察方式
UserDefaults
.
这个
Combine
框架为
用户默认值
,实际上是一个
关键价值观察出版商
首先让你
backgroundIsTransparent
属性的扩展
用户默认值
extension UserDefaults {
@objc var backgroundIsTransparent: Bool {
get {
guard object(forKey: PreferencesKeys.backgroundIsTransparent) != nil else { return true }
return bool(forKey: PreferencesKeys.backgroundIsTransparent)
}
set {
set(newValue, forKey: PreferencesKeys.backgroundIsTransparent)
}
}
}
在AppDelegate中导入
结合
并创建
Set
订阅的
import Combine
@main
class AppDelegate: NSObject, NSApplicationDelegate { ...
private var subscriptions = Set<AnyCancellable>()
和在
applicationDidFinishLaunching
添加发布者
func applicationDidFinishLaunching(_ aNotification: Notification) {
// .....
UserDefaults.standard.publisher(for: \.backgroundIsTransparent)
.sink { state in
print(state)
// do something with state
}
.store(in: &subscriptions)
}
使用您的方法的另一种选择是
userPreferences
一
@StateObject
@StateObject var userPreferences = UserPreferences.instance
并观察
背景是透明的
userPreferences.$backgroundIsTransparent
.sink { state in
print(state)
// do something with state
}
.store(in: &subscriptions)