重點
- 只支援 NSObject 的子物件
- 要加入關鍵字 dynamic
class album: NSObject {
dynamic var id:String?
dynamic var name:String?
dynamic var url:String?
}
class ViewController: UIViewController {
let ab:album = album()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ab.id = "0"
ab.name = "album1"
ab.url = "http://www.apple.com.tw"
ab.addObserver(self, forKeyPath: "url", options: [.old,.new], context: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
ab.removeObserver(self, forKeyPath: "url")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Button_Click(_ sender: Any) {
ab.url = "http://www.google.com.tw"
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "url"{
var newStr:String = "", oldStr:String = ""
if let dict = change?[.newKey] {
newStr = dict as! String
}
if let dict = change?[.oldKey]{
oldStr = dict as! String
}
print("old value = \(oldStr) -> new value = \(newStr)")
}
}
}