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

前端之家收集整理的这篇文章主要介绍了初探swift语言的学习笔记五(线程)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
作者:fengsh998
原文地址:http://blog.csdn.net/fengsh998/article/details/30354127
转载请注明出处
如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998支持我,谢谢!


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

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

  1. importUIKit
  2. classswiftThreadDemo:UIViewController
  3. {
  4. varqueue=NSOperationQueue()
  5. //init()
  6. //{
  7. ////alloc
  8. @H_502_101@//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. @H_502_101@//这里返回主线程,写需要主线程执行的代码
  23. println("这里返回主线程,写需要主线程执行的代码")
  24. })
  25. })
  26. functestNSThread()
  27. @H_502_101@//方式一 @H_502_101@//NSThread.detachNewThreadSelector("threadInMainMethod:",toTarget:self,withObject:nil)
  28. //方式二
  29. varmyThread=NSThread(target:self,selector:"threadInMainMethod:",object:nil)
  30. myThread.start()
  31. functhreadInMainMethod(sender:AnyObject)
  32. println("NSThreadrunning.")
  33. println("NSThreadover.")
  34. functestNSOperationQueue()
  35. @H_502_101@//func(op:NSOperation!)
  36. varmopt=myOperationThread()
  37. queue.addOperation(mopt)
  38. classmyOperationThread:NSOperation
  39. overridefuncstart()
  40. super.start()
  41. overridefuncmain()
  42. forvari=0;i<100000;i++
  43. println("NSOperationrunning.")
  44. println("NSOperationover.")
  45. }

调用

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

猜你在找的Swift相关文章