NSOperation的基本使用

//
//  ViewController.swift
//  NSOperation基本使用
//
//  Created by zhang 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.operationD()
    }
    // 线程间通信
    func operationD()
    {
        let queue = NSOperationQueue()
        queue.addOperationWithBlock { () -> Void in
            print(NSThread.currentThread())//<NSThread: 0x7fe1a0703c50>{number = 2, name = (null)}
            // 主队列(跟GCD里的主队列一样),到主队列更新ui
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                print(NSThread.currentThread())//<NSThread: 0x7fe1a0702d60>{number = 1, name = main}
            })
        }
    }
    // 往队列中直接添加block
    func operationC()
    {
        let queue = NSOperationQueue()
        // 不创建操作,直接往队列中直接添加block
        queue.addOperationWithBlock { () -> Void in
            print(NSThread.currentThread())
        }
    }
    // 往操作中添加block
    func operationB()
    {
        let queue = NSOperationQueue()
        let operation = NSBlockOperation { () -> Void in
            print(NSThread.currentThread())//<NSThread: 0x7fc53160b880>{number = 2, name = (null)}
            print("第一次执行")
        }
        // 往操作中添加block
        operation.addExecutionBlock { () -> Void in
            print(NSThread.currentThread())//<NSThread: 0x7fc5315492a0>{number = 3, name = (null)}
            print("第二次执行")
        }
        queue.addOperation(operation)
    }
    // 基本使用
    func operationA()
    {
        // 队列 (GCD里面的并发(全局)队列使用最多。所以NSOperation技术直接把GCD里面的并发队列封装起来)
        // NSOperationQueue队列,本质就是GCD里面的并发队列
        // 操作就是GCD里面异步执行的任务
        // 创建队列
        let queue = NSOperationQueue()
        // 创建操作
        let operation = NSBlockOperation { () -> Void in
            print(NSThread.currentThread())
        }
        // 添加操作到队列
        queue.addOperation(operation)
        // 使用start方法就是GCD中的同步执行
//        operation.start()
    }
}

标签: swift, iOS多线程, NSOperation

添加新评论