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

初探swift语言的学习笔记五(线程)

发布时间:2020-12-14 01:50:28 所属栏目:百科 来源:网络整理
导读:作者:fengsh998 原文地址: http://blog.csdn.net/fengsh998/article/details/30354127 转载请注明出处 如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号 fengsh998 来支持我,谢谢! swift 并没有使用新一套线程,使用OC源有的一套线程。下面以
作者:fengsh998
原文地址:http://blog.csdn.net/fengsh998/article/details/30354127
转载请注明出处
如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998来支持我,谢谢!


swift 并没有使用新一套线程,使用OC源有的一套线程。下面以例子来演示一下swift中使用线程。

其用包括常见的:NSThread,NSOperationQueue,GCG

[cpp] view plain copy
  1. importUIKit
  2. classswiftThreadDemo:UIViewController
  3. {
  4. varqueue=NSOperationQueue()
  5. //init()
  6. //{
  7. ////alloc
  8. //super.init()
  9. //}
  10. deinit
  11. {
  12. //dealloc
  13. }
  14. functestGCDThread()
  15. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{
  16. //这里写需要大量时间的代码
  17. forvari=0;i<100000;i++
  18. println("GCDthreadrunning.")
  19. }
  20. sleep(5);
  21. dispatch_async(dispatch_get_main_queue(),{
  22. //这里返回主线程,写需要主线程执行的代码
  23. println("这里返回主线程,写需要主线程执行的代码")
  24. })
  25. })
  26. functestNSThread()
  27. //方式一
  28. //NSThread.detachNewThreadSelector("threadInMainMethod:",toTarget:self,withObject:nil)
  29. //方式二
  30. varmyThread=NSThread(target:self,selector:"threadInMainMethod:",object:nil)
  31. myThread.start()
  32. functhreadInMainMethod(sender:AnyObject)
  33. println("NSThreadrunning.")
  34. println("NSThreadover.")
  35. functestNSOperationQueue()
  36. //func(op:NSOperation!)
  37. varmopt=myOperationThread()
  38. queue.addOperation(mopt)
  39. classmyOperationThread:NSOperation
  40. overridefuncstart()
  41. super.start()
  42. overridefuncmain()
  43. forvari=0;i<100000;i++
  44. println("NSOperationrunning.")
  45. println("NSOperationover.")
  46. }

调用:

    varst=swiftThreadDemo()
  1. st.testNSThread()
  2. sleep(2)
  3. st.testGCDThread()
  4. st.testNSOperationQueue()

(编辑:李大同)

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

    推荐文章
      热点阅读