Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic NSOperation subclass loses NSOperation functionality

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?

like image 235
Nevs12 Avatar asked Sep 29 '14 10:09

Nevs12


People also ask

What method in an NSOperation subclass contains the work the operation will perform?

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).

Is NSOperation thread safe?

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?

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.

How do you use NSOperationQueue in Objective C?

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.


1 Answers

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")
    }

}
like image 145
Sergey Topal Avatar answered Jan 03 '23 19:01

Sergey Topal