swift开启线程的3种方式(其实很简单的)

前端之家收集整理的这篇文章主要介绍了swift开启线程的3种方式(其实很简单的)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. import UIKit
  2. class swiftThreadDemo : UIViewController
  3. {
  4. var queue = NSOperationQueue()
  5. // init()
  6. // {
  7. // //alloc
  8. // super.init()
  9. // }
  10. deinit
  11. {
  12. //dealloc
  13. }
  14. func testGCDThread()
  15. {
  16. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{
  17. //这里写需要大量时间的代码
  18. for var i = 0; i < 100000; i++
  19. {
  20. println("GCD thread running.")
  21. }
  22. sleep(5);
  23. dispatch_async(dispatch_get_main_queue(),{
  24. //这里返回主线程,写需要主线程执行的代码
  25. println("这里返回主线程,写需要主线程执行的代码")
  26. })
  27. })
  28. }
  29. func testNSThread()
  30. {
  31. //方式一
  32. //NSThread.detachNewThreadSelector("threadInMainMethod:",toTarget:self,withObject:nil)
  33. //方式二
  34. var myThread = NSThread(target:self,selector:"threadInMainMethod:",object:nil)
  35. myThread.start()
  36. }
  37. func threadInMainMethod(sender : AnyObject)
  38. {
  39. for var i = 0; i < 100000; i++
  40. {
  41. println("NSThread running.")
  42. }
  43. sleep(5);
  44. println("NSThread over.")
  45. }
  46. func testNSOperationQueue()
  47. {
  48. //func (op: NSOperation!)
  49. var mopt = myOperationThread()
  50. queue.addOperation(mopt)
  51. }
  52. }
  53. class myOperationThread : NSOperation
  54. {
  55. override func start()
  56. {
  57. super.start()
  58. }
  59. override func main()
  60. {
  61. for var i = 0; i < 100000; i++
  62. {
  63. println("NSOperation running.")
  64. }
  65. println("NSOperation over.")
  66. }
  67. }
调用
  1. var st = swiftThreadDemo()
  2. st.testNSThread()
  3. sleep(2)
  4. st.testGCDThread()
  5. st.testNSOperationQueue()
这就常用开启线程的3种方式

猜你在找的Swift相关文章