首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Swift中使用UserDefaults的KVO?

如何在Swift中使用UserDefaults的KVO?
EN

Stack Overflow用户
提问于 2017-05-14 19:13:29
回答 1查看 15.1K关注 0票数 26

我正在重写应用程序的一部分,发现了以下代码:

代码语言:javascript
复制
fileprivate let defaults = UserDefaults.standard

func storeValue(_ value: AnyObject, forKey key:String) {
    defaults.set(value, forKey: key)
    defaults.synchronize()

    NotificationCenter.default.post(name: Notification.Name(rawValue: "persistanceServiceValueChangedNotification"), object: key)
}
func getValueForKey(_ key:String, defaultValue:AnyObject? = nil) -> AnyObject? {
    return defaults.object(forKey: key) as AnyObject? ?? defaultValue
}

按住CMD键并单击行defaults.synchronize()时,我看到synchronize已计划弃用。这是在代码中编写的:

代码语言:javascript
复制
/*!
     -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.

     -synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized...
     - ...before reading in order to fetch updated values: remove the synchronize call
     - ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
     - ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
     - ...for any other reason: remove the synchronize call
     */

据我所知,我的用法符合第二种描述:写完后同步,以便通知其他人。

它建议使用KVO进行排卵,但如何进行呢?当我搜索这个的时候,我发现了一堆稍微老一点的Objective-C示例。观察UserDefaults的最佳实践是什么?

EN

回答 1

Stack Overflow用户

发布于 2021-03-19 19:18:58

从iOS 13开始,现在有了一种更酷的方式来实现这一点,使用Combine:

代码语言:javascript
复制
import Foundation
import Combine

extension UserDefaults {
    /// Observe UserDefaults for changes at the supplied KeyPath.
    ///
    /// Note: first, extend UserDefaults with an `@objc dynamic` variable
    /// to create a KeyPath.
    ///
    /// - Parameters:
    ///   - keyPath: the KeyPath to observe for changes.
    ///   - handler: closure to run when/if the value changes.
    public func observe<T>(
        _ keyPath: KeyPath<UserDefaults, T>,
        handler: @escaping (T) -> Void)
    {
        let subscriber = Subscribers.Sink<T, Never> { _ in }
            receiveValue: { newValue in
                handler(newValue)
            }
        
        self.publisher(for: keyPath, options: [.initial, .new])
            .subscribe(subscriber)
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43963220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档