Swift:实现KVO的willSet、didSet

一、KVO

kvo键值观察者

Swift继承NSObject的KVO

swift 实现kvo需要两个条件,第一要是NSObject的子类,第二要在观察的属性添加@objc dynamic

class Animal: NSObject {
    @objc dynamic var name: String = "ob";
}

class ViewController: UIViewController {
    let dog = Animal.init();
    var observation: NSKeyValueObservation?
    override func viewDidLoad() {
        super.viewDidLoad()
        observation = dog.observe(\Animal.name, options: [.new,.old]) { (Animal, change) in
            if let name = change.oldValue {
                print("old:" + name)
            }
            if let name = change.newValue {
                print("new:" + name)
            }
        }
	}
	
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dog.name = "i_am_Tom";
    }
}

打印

old:ob
new:i_am_Tom
Swift中set方法

有set和get方法

class Animal {
    var _name:String = "";
    var name:String {
        set {
            _name = newValue;
        }
        get {
            return _name;
        }
    };
}

如果没有get方法

class Animal {
    var _name:String = "";
    var name:String = "ob" {
        set {
            _name = newValue;
        }
    };
}

注意:一旦实现了willSetdidSet方法,就不能实现set和get方法,set\getwillset只能存在一种

class Animal {
    var _name:String = "";
    var name:String = "ob" {
        willSet {
           // code ... 
        }
        didSet {
            
        }
    };
}

Swift非NSObject实现KVO

主要是利用set方法中的willSetdidSet特性;

public class OBKVO<Type>  {
    
    private var callback:((_ oldValue:Type, _ newValue:Type) ->())?;
    init(_ value: Type) {
        self.value = value;
    }
    
    var value: Type {
        didSet {
            self.callback!(oldValue,value);
        }
    }
    func addObserver(_ callback:@escaping (_ oldValue: Type, _ newValue:Type) ->())  {
        self.callback = callback;
    }
}


class Person {
    var name: OBKVO<String>;
    init(name :String ) {
        self.name = OBKVO.init(name);
    }
}

调用

class ViewController: UIViewController {

    let person = Person.init(name: "obnb");
    override func viewDidLoad() {
        super.viewDidLoad()
        person.name.addObserver { (old, new) in
            print("old is \(old),-- new vlaue is \(new)");
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        person.name.value = "i_am_Mack";
        
    }
}

打印结果:

old is obnb,-- new vlaue is i_am_Mack
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值