Swift-Multi-threaded implementations (2)-Nsoperation and Nsoperationqueue

Source: Internet
Author: User
Tags uikit

1,swift continues to use Object-c's original set of threads, including three multithreaded programming techniques:
(1) Nsthread
(2) Cocoa nsoperation (Nsoperation and Nsoperationqueue)
(3) Grand Central Dispath (GCD)


2, this article emphatically introduces Cocoa nsoperation
Cocoa Nsoperation does not need to care about thread management and data synchronization, you can focus on what you need to do. The related classes are nsoperation and nsoperationqueue. Where Nsoperation is an abstract class, it must use its subclasses to implement it or use its defined subclasses: Nsblockoperation. Creates an object of the Nsoperation subclass and adds the object to the Nsoperationqueue queue for execution.

3, two ways of using nsoperation(1) directly with the defined sub-class: Nsblockoperation.
1234567891011121314151617181920212223242526272829 import UIKitclass 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 imageUrl = "http://hangge.com/blog/images/logo.png"        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) Succession nsoperation

The object of the Nsoperation subclass is then placed in the Nsoperationqueue queue, and once the object is added to the queue, the queue begins to process the object until all operations of the object are completed, and then it is freed by the queue.
1234567891011121314151617181920212223242526 import UIKitclass 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 imageUrl = "http://hangge.com/blog/images/logo.png"        var data = NSData(contentsOfURL: NSURL(string: imageUrl)!, options: nil, error: nil)        println(data?.length)    }}


4, set the number of run queue concurrency

Many nsoperation can be added to the Nsoperationqueue queue, and nsoperationqueue can be seen as a thread pool that can add operations (nsoperation) to the queue. You can set the number of threads in the thread pool, which is the number of concurrent operations. By default, -1,-1 means there is no limit so that you can run all the operations in the queue at the same time.
12 //设置并发数queue.maxConcurrentOperationCount = 5


5, cancel all operations on the queue

12 //取消所有线程操作queue.cancelAllOperations()


6, each nsoperation completion will have a callback to indicate the end of the task

1234567 //定义一个回调varcompletionBlock:(() -> Void)?//给operation设置回调operation.completionBlock = completionBlockdispatch_after(dispatch_time(DISPATCH_TIME_NOW, 4), dispatch_get_main_queue(), {    println("Complete")})

Swift-Multi-threaded implementations (2)-Nsoperation and Nsoperationqueue

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.