OperationQueue执行时未调用操作子类“ main”方法?

时间:2018-11-08 10:20:08

标签: ios swift multithreading nsoperationqueue operation

我创建了一个继承自基类“ Operation”的子类“ MyOperation”。我在“ MyOperation”中添加了一个函数,该函数在实例化该类时被调用。但是,在创建操作类并将其添加到操作队列时,不会调用“ main”方法。

class MyOperation: Operation {

let iterations:Int
let tag:String

init(iterations:Int, tag:String) {
    self.iterations = iterations
    self.tag = tag
}

/**
 When Operation queue begins execution it calls the main method without parameters, so any parameters needed should be passed through initializer.
 **/

override func main() {
    performCalculation()
}

func performCalculation(){
    let start = CFAbsoluteTimeGetCurrent()
    for _ in 0..<iterations {

        self.doCalculations()
    }
    let end = CFAbsoluteTimeGetCurrent()
    print("time for \(tag):\(end-start)")
}

func doCalculations() {

    let x = 100
    let y = x*x
    let _ = y/x
}

}

我正在从Viewcontroller的ViewDidLoad调用MyOperation类。

override func viewDidLoad() {
    super.viewDidLoad()
   createOperationQueuewithMyOperationClass()
}

func createOperationQueuewithMyOperationClass(){


    let operationQueue = OperationQueue()
    operationQueue.addOperation {
        MyOperation(iterations: 10000000, tag: "Operation-1")
    }

    operationQueue.addOperation {
      MyOperation(iterations: 1000, tag: "Operation-2")
    }

    operationQueue.addOperation {
      MyOperation(iterations: 100000, tag: "Operation-3")
    }
}

1 个答案:

答案 0 :(得分:0)

您使用了错误的addOperation。您所简单地将一个块操作添加到队列中,而该块正在创建该操作,而对其不执行任何操作。您想要这个:

operationQueue.addOperation(MyOperation(iterations: 100000, tag: "Operation-3"))

请注意缺少括号{ ... }和括号。

您正在呼叫addOperation(() -> Void)而不是addOperation(Operation)