I have created a subclass "MyOperation" inheriting from base class "Operation". I have added a function in "MyOperation" which gets called when the class in instantiated. However the "main" method is not getting called when the operation class is created and added to an Operation Queue.
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
}
}
I am calling MyOperation class from ViewDidLoad of a viewcontroller.
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")
}
}
You are using the wrong addOperation
. The one you have simply adds a block operation onto the queue and the block is creating the operation and doing nothing with it. You want this:
operationQueue.addOperation(MyOperation(iterations: 100000, tag: "Operation-3"))
Note the lack of braces { ... }
and the parentheses instead.
You were calling addOperation(() -> Void)
instead of addOperation(Operation)