1,Swift继续使用Object-C原有的一套线程,包括三种多线程编程技术:
(1)NSThread
(2)Cocoa NSOperation(NSOperation和NSOperationQueue)
(3)Grand Central Dispath(GCD)
2,本文着重介绍Cocoa NSOperation
Cocoa NSOperation不需要关心线程管理和数据同步的事情,可以把精力放在自己需要执行的操作上。相关的类有NSOperation和 NSOperationQueue。其中NSOperation是个抽象类,使用它必须用它的子类,可以实现它或者使用它定义好的子 类:NSBlockOperation。创建NSOperation子类的对象,把对象添加到NSOperationQueue队列里执行。
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" )
}) |