Today I've met one weird issue when I was trying to 'generalize' my 'CoreData importing operations'.
It appeared that if I create a generic subclass of NSOperation the main()
func won't be called.
Simple example:
class MyOperation<T: NSObject>: NSOperation {
override func main() {
println("My operation main was called")
}
}
If you create an instance of this class and add it to the operationQueue
you will see that it's main()
isn't actually called.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.operationQueue = NSOperationQueue()
let operation = MyOperation<NSString>()
self.operationQueue!.addOperation(operation)
}
Operation simply transits from ready
to executing
and to finished
state without calling main()
.
If I remove generic annotation <T: NSObject>
from MyOperation
class it will work fine.
How is this possible? Am I missing something here?
You typically execute operations by adding them to an operation queue (an instance of the NSOperationQueue class). An operation queue executes its operations either directly, by running them on secondary threads, or indirectly using the libdispatch library (also known as Grand Central Dispatch).
You can safely use a single NSOperationQueue object from multiple threads without creating additional locks to synchronize access to that object. Operation queues use the Dispatch framework to initiate the execution of their operations.
What is NsOperationQueue in Swift? A queue that regulates the execution of operations. NSOperation represents a single unit of work. It's an abstract class that offers a useful, thread-safe structure for modeling state, priority, dependencies, and management.
NSOperationQueue *q = [[NSOperationQueue alloc] init]; /* Data to process */ NSData *data = [@"Hello, I'm a Block!" dataUsingEncoding: NSUTF8StringEncoding]; /* Push an expensive computation to the operation queue, and then * display the response to the user on the main thread.
Workaround: You can create NSOperation subclass (no generic), override main and call you own 'execute' func, which can be overriden by generic subclasses. Example:
class SwiftOperation : NSOperation {
final override func main() {
execute()
}
func execute() {
}
}
class MyOperation<T> : SwiftOperation {
override func execute() {
println("My operation main was called")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With