美文网首页
8.25 KVC & KVO 观察者

8.25 KVC & KVO 观察者

作者: jayck | 来源:发表于2016-09-07 21:01 被阅读4次

    创建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<Void>) {
            print(keyPath)
            print(object)
            print(change)
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    

    运行结果如下:

    Paste_Image.png

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

    相关文章

      网友评论

          本文标题:8.25 KVC & KVO 观察者

          本文链接:https://www.haomeiwen.com/subject/ditsettx.html