|  尽管swift作为一门新语言,但还保留了许多OC的机制,使得swift和OC更好的融合在一起。如果没有OC基础的先GOOGLE一下。
  如:KVO,DELEGATE,NOTIFICATION。  详见DEMO。    
  
 测试: 
   importFoundation  @objc protocolkvoDemoDelegate{ funcwillDoSomething() @optionalfuncdidDoSomething() }  letntfname="test_notification" classkvoDemo:NSObject { vardelegate:kvoDemoDelegate! varpresult:Double=0.0 varresult:Double{ get{returnpresult; } set{ self.presult=newValue init() funcdoSomething() { ifletyet=self.delegate? delegate!.willDoSomething()for_in1..5 println("i'mdoingnow,don'ttouchme,please.") delegate!.didDoSomething!() funcnotificationPost() letntf=NSNotificationCenter.defaultCenter() ntf.postNotificationName(ntfname,object:nil,userInfo:nil) deinit }     classViewController:UIViewController,kvoDemoDelegate{ 
    overridefuncobserveValueForKeyPath(keyPath:String?,ofObject:AnyObject?,change:NSDictionary?,context:CMutableVoidPointer)ifkeyPath=="result" varnewvalue:AnyObject?=change?.objectForKey("new"); println("thenewvalueis(newvalue)")//delegate println("iwilldoit.") funcdidDoSomething() println("ihaddoit.")  funconRecviceNotification(notification:NSNotification) println("Recevicenotification(notification)") overridefuncviewDidLoad(){ super.viewDidLoad()//Doanyadditionalsetupafterloadingtheview,typicallyfromanib. varkvo=kvoDemo() kvo.addObserver(self,forKeyPath:"result",options:NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Old,context:nil) kvo.result=280.0 kvo.removeObserver(self,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> kvo.delegate=self kvo.doSomething() letntf=NSNotificationCenter.defaultCenter() ntf.addObserver(self,selector:"onRecviceNotification:",name:ntfname,object:nil) kvo.notificationPost() ntf.removeObserver(self) } 结果:
      thenewvalueis280 
   iwilldoit. i'mdoingnow,don'ttouchme,please. i'mdoingnow,please. ihaddoit. RecevicenotificationNSConcreteNotification0x10be60930{name=test_notification}  (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |