微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

作者:fengsh998
原文地址:http://blog.csdn.net/fengsh998/article/details/32715833
转载请注明出处
如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998支持我,谢谢!


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

如:KVO,DELEGATE,NOTIFICATION。

详见DEMO。

  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}

原文地址:https://www.jb51.cc/swift/326032.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐