Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active July 2, 2018 11:55
Show Gist options
  • Save KentarouKanno/f1311f4464fb998ab49da0b1de432cc1 to your computer and use it in GitHub Desktop.
Save KentarouKanno/f1311f4464fb998ab49da0b1de432cc1 to your computer and use it in GitHub Desktop.

KVO Swift4

参考URL: Swift4のKVOに感動した。
WKWebView Progress(Swift4)

import UIKit

class ViewController: UIViewController {
    
    private var observers: [NSKeyValueObservation] = []
    private let kvo = KVOSample()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        observers.append(kvo.observe(\.value, options: [.new, .old]){_ ,change in
            print("new =",change.newValue ?? "")
            print("old =", change.oldValue ?? "")
        })
    }
    
    @IBAction func up(_ sender: UIButton) {
        kvo.value += 1
    }
    
    // KVO Remove
    @IBAction func removeKVO(_ sender: UIButton) {
        observers.forEach { $0.invalidate() }
        observers.removeAll()
    }
}

// KVO Class
class KVOSample: NSObject{
    // 監視プロパティ
    @objc dynamic var value:Int = 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment