原创BLog,转载请注明出处
Swift中使用KVC和KVO的类都必须必须继承自NSObject
KVC
key-value codingclass TestForKVC:NSObject{ var hwcCSDN = "hello world" } var instance = TestForKVC() var value = instance.valueForKey("hwcCSDN") as String instance.setValue("hello hwc",forKey:"hwcCSDN")
class ToObserver:NSObject{ dynamic var hwcDate = NSDate() func updateDate(){ hwcDate = NSDate() } }
private var mycontext = 0
class TestForCSDN:UIViewController{ var testVariable = ToObserver() override func viewDidLoad(){ super.viewDidLoad() testVariable.addObserver(self,forKeyPath:"hwcDate",options:.New,context:&mycontext) } deinit{ testVariable.removeObserver(self,forKeyPath:"hwcDate") } overfide func observeValueForKeyPath(keyPath:String,ofObject:AnyObject,change:[NSObject:AnyObject],context:UnsafeMutablePointer<Void>){ if(context == &mycontext){ println("Changed to:\(change[NSKeyValueChangeNewKey]!)") } } }
这样,就可以在函数observeValueForKeyPath检测到变化了
原文:http://blog.csdn.net/hello_hwc/article/details/40590955