学习swift 《kvc和kvo的简单使用》

kvc和kvo我是对照着ios写的,有什么不对的地方多多指教


先建两个简单的model类,Animal类和dog类没有任何继承关系
如下:
import UIKit

class Animal: NSObject {

    var name:String = ""
    var dog:Dog?
    
    var arr = NSMutableArray();
    
    
}


import UIKit

class Dog: NSObject {

    var name:String = "old_name"
    var age:Int = 1;
    
    
    
}


kvc的使用
然后再viewControl中添加一个按钮,然后在按钮方法中操作
func buttonAction(_ button:UIButton) {
        
        let anima = Animal();
        //赋值
        anima.name = "小狗";
       print("使用kvc之前name是:"+anima.name);
        //forKey
        anima.setValue("kvc小狗", forKey: "name")
        print("使用kvc设置name:"+anima.name)
        //forKeypath,使用forkeypath可以一层层往下查询属性进行赋值
        anima.dog = Dog();
        anima.dog?.name = "dog"
        print("未使用forkeyPath:"+(anima.dog?.name)!);
        anima.setValue("kvc_forkeyPath_dog", forKeyPath: "dog.name")
        print("使用forkeyPath:"+(anima.dog?.name)!)
    
        //取值
        let str = anima.value(forKey: "name")
        print("kvc_forKey取值:",str!)
        
        let str2 = anima.value(forKeyPath: "dog.name")
        print("kvc_forKeyPath取值:",str2!)
        
        
        //其他小技巧
        
        let dog1 = Dog();
        dog1.name = "dog1_name";
        dog1.age = 1;
        
        let dog2 = Dog();
        dog2.name = "dog2_name";
        dog2.age = 2;
        
        let dog3 = Dog();
        dog3.name = "dog3_name";
        dog3.age = 3;
        
        let dog4 = Dog();
        dog4.name = "dog4_name";
        dog4.age = 4;
        
        anima.arr = [dog1,dog2,dog3,dog4];
        
        //取出数组元素中的那么属性
      let nameArr =  anima.value(forKeyPath:"arr.name")
        print("取出数组元素中的那么属性",nameArr!)
        //对元素内的元素属性@sum(求和),@avg(求平均数)
        let sortArr = anima.value(forKeyPath: "[email protected]")
        print("求和:",sortArr!)
        
    }


kvo的使用
首先在viewcontroller中创建一个全局的dog属性
let dogMode = Dog()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        //添加监听方法
//第一个监听的对象
//第二个要监听的属性
//第三个监听的value
//第四填nil
        dogMode.addObserver(self, forKeyPath:"name", options: .new, context: nil)
        
    }
//重写监听方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        print("被观察的属性:",keyPath!)
        print("被观察对象:",object!)
         print("存储值的字典newKey:",change![NSKeyValueChangeKey.newKey]!)
    
    }
//点击按钮设置name的值,
func buttonAction(_ button:UIButton) {
        //使用kvo,一定要使用kvc对属性进行赋值,否则监听不到值的改变
        dogMode.setValue("新的kvo_dog_name", forKeyPath:"name")  
    }


你可能感兴趣的:(swift)