Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift语言的学习笔记八(保留了许多OC的实现)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

尽管swift作为一门新语言,但还保留了许多OC的机制,使得swift和OC更好的融合在一起。如果没有OC基础的先GOOGLE一下。 如:KVO,DELEGATE,NOTIFICATION。 详见DEMO。 [cpp]  view plain copy import Foundation      @objc   // 需要打开objc标识,否则@optional编译出错      protoco

尽管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@R_489_7101@g?,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. }

大佬总结

以上是大佬教程为你收集整理的swift语言的学习笔记八(保留了许多OC的实现)全部内容,希望文章能够帮你解决swift语言的学习笔记八(保留了许多OC的实现)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。