自定义NSOperation类

//
//  ViewController.swift
//  缓存类使用
//
//  Created by admin on 16/2/24.
//  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?) {
        let queue = NSOperationQueue()
        let operation = MyOperation()
        queue.addOperation(operation)
        // 线程执行完毕调用的方法
        operation.completionBlock = {
            ()->(Void) in
            print("线程执行完毕,输出信息")
        }
    }
}

class MyOperation: NSOperation {
    // 注意点:需要自己手动添加自动释放池
    // 自定义的操作,可以取消
    override func main() {
        super.main()
        func autorelasepool(code:()->(Void)){
            code()
        }
        autorelasepool { () -> (Void) in
            // 如果操作在队列里,还没有调度,就直接return
            if self.cancelled == true
            {
                return
            }
            NSThread.sleepForTimeInterval(2)
            print("执行结束")
        }
    }
}

标签: swift, iOS多线程

添加新评论