标签:
1,Swift继续使用Object-C原有的一套线程,包括三种多线程编程技术:
(1)NSThread
(2)Cocoa NSOperation(NSOperation和NSOperationQueue)
(3)Grand Central Dispath(GCD)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() var operation: NSBlockOperation = NSBlockOperation (block: { [ weak self ] in self ?.downloadImage() return }) //创建一个NSOperationQueue实例并添加operation var queue: NSOperationQueue = NSOperationQueue () queue.addOperation(operation) } //定义一个下载图片的方法,线程调用 func downloadImage(){ var data = NSData (contentsOfURL: NSURL (string: imageUrl)!, options: nil , error: nil ) println (data?.length) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } |
(2)继承NSOperation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import UIKit class ViewController : UIViewController { override func viewDidLoad() { super .viewDidLoad() //创建线程对象 var downloadImageOperation: DownloadImageOperation = DownloadImageOperation () //创建一个NSOperationQueue实例并添加operation var queue: NSOperationQueue = NSOperationQueue () queue.addOperation(downloadImageOperation) } override func didReceiveMemoryWarning() { super .didReceiveMemoryWarning() } } class DownloadImageOperation : NSOperation { override func main(){ var data = NSData (contentsOfURL: NSURL (string: imageUrl)!, options: nil , error: nil ) println (data?.length) } } |
4,设置运行队列并发数
1
2
|
//设置并发数 queue.maxConcurrentOperationCount = 5 |
5,取消队列所有操作
1
2
|
//取消所有线程操作 queue.cancelAllOperations() |
6,每个NSOperation完成都会有一个回调表示任务结束
1
2
3
4
5
6
7
|
//定义一个回调 var completionBlock:(() -> Void )? //给operation设置回调 operation.completionBlock = completionBlock dispatch_after(dispatch_time( DISPATCH_TIME_NOW , 4), dispatch_get_main_queue(), { println ( "Complete" ) }) |
Swift - 多线程实现方式(2) - NSOperation和NSOperationQueue
标签:
原文地址:http://www.cnblogs.com/Free-Thinker/p/4841134.html