加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift语言的学习笔记八(保留了许多OC的实现)

发布时间:2020-12-14 02:17:53 所属栏目:百科 来源:网络整理
导读:尽管swift作为一门新语言,但还保留了许多OC的机制,使得swift和OC更好的融合在一起。如果没有OC基础的先GOOGLE一下。 如:KVO,DELEGATE,NOTIFICATION。 详见DEMO。 [cpp] view plain copy importFoundation @objc /

尽管swift作为一门新语言,但还保留了许多OC的机制,使得swift和OC更好的融合在一起。如果没有OC基础的先GOOGLE一下。

如:KVO,DELEGATE,NOTIFICATION。

详见DEMO。

[cpp] view plain copy
  1. importFoundation
  2. @objc//需要打开objc标识,否则@optional编译出错
  3. protocolkvoDemoDelegate{
  4. funcwillDoSomething()
  5. @optionalfuncdidDoSomething()//可选实现,
  6. }
  7. letntfname="test_notification"
  8. classkvoDemo:NSObject//不写NSObject默认就是从NSObject来的
  9. {
  10. vardelegate:kvoDemoDelegate!
  11. varpresult:Double=0.0
  12. varresult:Double{
  13. get{
  14. returnpresult;
  15. }
  16. set{
  17. self.presult=newValue
  18. init()
  19. funcdoSomething()
  20. {
  21. ifletyet=self.delegate?
  22. delegate!.willDoSomething()
  23. for_in1..5
  24. println("i'mdoingnow,don'ttouchme,please.")
  25. delegate!.didDoSomething!()
  26. funcnotificationPost()
  27. letntf=NSNotificationCenter.defaultCenter()
  28. ntf.postNotificationName(ntfname,object:nil,userInfo:nil)
  29. deinit
  30. }
测试:

    classViewController:UIViewController,kvoDemoDelegate{
  1. //KVO
  2. overridefuncobserveValueForKeyPath(keyPath:String?,ofObject:AnyObject?,change:NSDictionary?,context:CMutableVoidPointer)
  3. ifkeyPath=="result"
  4. varnewvalue:AnyObject?=change?.objectForKey("new");
  5. println("thenewvalueis(newvalue)")
  6. //delegate
  7. println("iwilldoit.")
  8. funcdidDoSomething()
  9. println("ihaddoit.")
  10. //notification
  11. funconRecviceNotification(notification:NSNotification)
  12. println("Recevicenotification(notification)")
  13. overridefuncviewDidLoad(){
  14. super.viewDidLoad()
  15. //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
  16. varkvo=kvoDemo()
  17. kvo.addObserver(self,forKeyPath:"result",options:NSKeyValueObservingOptions.New|NSKeyValueObservingOptions.Old,context:nil)
  18. kvo.result=280.0
  19. 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
  20. kvo.doSomething()
  21. letntf=NSNotificationCenter.defaultCenter()
  22. ntf.addObserver(self,selector:"onRecviceNotification:",name:ntfname,object:nil)
  23. kvo.notificationPost()
  24. ntf.removeObserver(self)
  25. }

结果:

    thenewvalueis280
  1. iwilldoit.
  2. i'mdoingnow,don'ttouchme,please.
  3. i'mdoingnow,please.
  4. ihaddoit.
  5. RecevicenotificationNSConcreteNotification0x10be60930{name=test_notification}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读