操作队列NSOperation
NSOperation有3个有用的布尔属性,finished、 cancelled和ready
一旦操作执行完成,finisher将被置为true
一旦操作被取消,cancelled将被置为true
一旦准备即将被执行,ready将被置为true
3.1
//声明变量
let queue = NSOperationQueue()
@IBAction func downloadImages(sender: UIButton) {
queue.addOperationWithBlock { () -> Void in
let image1 = Downloader.downloadImageWithURL(self.imageUrls[0])
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.imageViewArr[0].image = image1
})
}
// 1. Create a NSBlockOperation object
let op2 = NSBlockOperation { () -> Void in
let image2 = Downloader.downloadImageWithURL(self.imageUrls[1])
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.imageViewArr[1].image = image2
})
}
// 2. Set finish callback
op2.completionBlock = { print("image2 downloaded") }
// 3. Add to operation queue manually
// queue.addOperation(op2)
let op3 = NSBlockOperation { () -> Void in
let image3 = Downloader.downloadImageWithURL(self.imageUrls[2])
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.imageViewArr[2].image = image3
})
}
op3.completionBlock = { print("image3 cancelled: \(op3.cancelled)") }
let op4 = NSBlockOperation { () -> Void in
let image4 = Downloader.downloadImageWithURL(self.imageUrls[3])
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.imageViewArr[3].image = image4
})
}
op4.completionBlock = { print("image4 downloaded") }
// 依赖关系
op3.addDependency(op4)
op2.addDependency(op3)
queue.addOperation(op4)
queue.addOperation(op3)
queue.addOperation(op2)
}
@IBAction func cancelDown(sender: UIButton) {
queue.cancelAllOperations()
}