How to use KVO for UserDefaults in Swift?

前端 未结 4 1543
耶瑟儿~
耶瑟儿~ 2021-02-04 01:00

I\'m rewriting parts of an app, and found this code:

fileprivate let defaults = UserDefaults.standard

func storeValue(_ value: AnyObject, forKey key:String) {
          


        
4条回答
  •  时光说笑
    2021-02-04 01:49

    As of iOS 11 + Swift 4, the recommended way (according to SwiftLint) is using the block-based KVO API.

    Example:

    Let's say I have an integer value stored in my user defaults and it's called greetingsCount.

    First I need to extend UserDefaults:

    extension UserDefaults {
        @objc dynamic var greetingsCount: Int {
            return integer(forKey: "greetingsCount")
        }
    }
    

    This allows us to later on define the key path for observing, like this:

    var observer: NSKeyValueObservation?
    
    init() {
        observer = UserDefaults.standard.observe(\.greetingsCount, options: [.initial, .new], changeHandler: { (defaults, change) in
            // your change logic here
        })
    }
    

    And never forget to clean up:

    deinit {
        observer?.invalidate()
    }
    

提交回复
热议问题