Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

swift - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...