8.25 KVC & KVO 观察者

创建2个类,动物和食物

import UIKit

class Animal: NSObject {
    var name: String!
    var age: Int!
    var weight: Double!
    
    var food: Food!
}

import UIKit

class Food: NSObject {
    var name: String!
}

import UIKit

class ViewController: UIViewController {
    let ani = Animal()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        ani.name = "Zhangsan"
        
        print(ani.name)
        
        //KVC - Key value coding
        //keyPath
        //无视所有访问权限控制
               //Swift中,如果变量前面写了private,就不能用 
        ani.setValue("Lisi", forKey: "name")
        print(ani.name)
        
        print(ani.valueForKey("name"))
        
        let food = Food()
        food.name = "骨头"
        
        ani.food = food
        
        print(ani.food.name)
        
        ani.setValue("耗子", forKeyPath: "food.name")
        print(ani.food.name)
        
        print(ani.valueForKeyPath("food.name"))
        
        //KVO -     key-value observing
        //self观察ani的name属性的变化
        ani.addObserver(self, forKeyPath: "name", options: [.New], context: nil)
        
        //会通知观察者
        ani.setValue("Dog", forKeyPath: "name")
//        ani.name = "Cat"
        ani.setValue("Cat", forKey: "name")
        
        ani.removeObserver(self, forKeyPath: "name")
        
        //contentOffset/contentSize/contentInset
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer) {
        print(keyPath)
        print(object)
        print(change)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

运行结果如下:

8.25 KVC & KVO 观察者_第1张图片
Paste_Image.png

Optional( )中可以看到哪些值发生了变化。

你可能感兴趣的:(8.25 KVC & KVO 观察者)