NSOperation高级属性及总结

//
//  ViewController.swift
//  NSOperation使用
//
//  Created by admin on 16/2/22.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.operationB()
    }
    /**
     GCD --> iOS 4.0
     - 将任务(block)添加到队列(串行/并发(全局)),指定 执行任务的方法(同步(阻塞)/异步)
     - 拿到 dispatch_get_main_queue()。 线程间通信
     - NSOperation无法做到,一次性执行,延迟执行,调度组(op相对复杂)


     NSOperation ----> iOS 2.0 (后来苹果改造了NSOperation的底层)
     - 将操作(异步执行)添加到队列(并发/全局)
     - [NSOperationQueue mainQueue] 主队列。 任务添加到主队列, 就会在主线程执行
     - 提供了一些GCD不好实现的,”最大并发数“
     - 暂停/继续 --- 挂起
     - 取消所有的任务
     - 依赖关系
     */

     /**
     小结一下:
     只要是NSOperation的子类 就能添加到操作队列
     - 一旦操作添加到队列, 就会自动异步执行
     - 如果没有添加到队列, 而是使用start方法,会在当前线程执行操作
     - 如果要做线程间通信,可以使用[NSOperationQueue mainQueue]拿到主队列,往主队列添加操作(更新UI)
     */
    /**负责调度所有的操作*/
    let queue = NSOperationQueue()
    func operationB()
    {
        let operationA = NSBlockOperation { () -> Void in
            print(NSThread.currentThread())
            print("下载")
        }
        let operationB = NSBlockOperation { () -> Void in
            print(NSThread.currentThread())
            print("解压")
        }
        let operationC = NSBlockOperation { () -> Void in
            print(NSThread.currentThread())
            print("更新UI")
        }
        // 指定任务之间的依赖关系 -- 依赖关系可以跨队列(可以在子线程下载完,到主线程更新UI)
        operationB.addDependency(operationA)
        operationC.addDependency(operationB)
        // 注意点:一定不要出现循环依赖关系
        // operationA.addDependency(operationC)
        NSOperationQueue.mainQueue().addOperation(operationC)
        queue.addOperations([operationA,operationB], waitUntilFinished: true)

    }

    // MARK: 取消队列里的所有操作
    // “取消操作,并不会影响队列的挂起状态”
    @IBAction func clearQueue(sender: AnyObject) {
        self.queue.cancelAllOperations()// 取消队列的所有操作,会把任务从队列里面全部删除
        self.queue.suspended = false // (只要是取消了队列的操作,我们就把队列处于启动状态。以便于队列的继续)
    }
    // MARK: 暂停/继续 (对队列的暂停和继续)
    @IBAction func suspend(sender: AnyObject) {
        // 判断操作的数量,当前队列里面是不是有操作
        if self.queue.operationCount <= 0
        {
            return
        }
        // 队列的挂起以后,队列里面的操作还在
        self.queue.suspended = !self.queue.suspended
    }
    // 最大并发数
    func operationA()
    {
        // 设置最大的并发数是2 (最大并发数,不是线程的数量。 而是同时执行的操作的数量)
        queue.maxConcurrentOperationCount = 2
        for var i = 0;i < 10;i++
        {
            let operation = NSBlockOperation(block: { () -> Void in
                NSThread.sleepForTimeInterval(2)
                print(NSThread.currentThread())
                print(i)
            })
            queue.addOperation(operation)
        }
    }
}

标签: swift, iOS多线程, NSOperation

添加新评论