Swift
发布时间:2022-03-31 发布网站:大佬教程 code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift语言的学习笔记五(线程),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
概述
swift 并没有使用新一套线程,使用OC源有的一套线程。下面以例子来演示一下swift中使用线程。 其用包括常见的:NSThread,NSOperationQueue,GCG [cpp] view plain copy import UIKit
class swiftThreadDemo : UIViewController
{ var queue = NSOp
swift 并没有使用新一套线程,使用OC源有的一套线程。下面以例子来演示一下swift中使用线程。
其用包括常见的:NSThread,NSOperationQueue,GCG
- importUIKit
-
-
- classswiftThreadDemo:UIViewController
- {
- varqueue=NSOperationQueue()
-
-
- ////alloc
@H_450_80@//super.init()
- //}
- deinit
- {
- //dealloc
- }
- functestGCDThread()
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{
- //这里写需要大量时间的代码
- forvari=0;i<100000;i++
- println("GCDthreadrunning.")
- }
- sleep(5);
- dispatch_async(dispatch_get_main_queue(),{
@H_450_80@//这里返回主线程,写需要主线程执行的代码
- println("这里返回主线程,写需要主线程执行的代码")
- })
- })
- functestNSThread()
@H_450_80@//方式一
@H_450_80@//NSThread.detachNewThreadSELEctor("threadInMainMethod:",@R_605_10586@rget:self,withObject:nil)
- //方式二
- varmyThread=NSThread(target:self,SELEctor:"threadInMainMethod:",object:nil)
- myThread.start()
- functhreadInMainMethod(sender:AnyObject)
- println("NSThreadrunning.")
- println("NSThreadover.")
- functestNSOperationQueue()
@H_450_80@//func(op:NSOperation!)
- varmopt=myOperationThread()
- queue.addoperation(mopt)
- class@H_22_32@myOperationThread:NSOperation
- overridefuncstart()
- super.start()
- overridefuncmain()
- forvari=0;i<100000;i++
- println("NSOperationrunning.")
- println("NSOperationover.")
- }
调用: