Generic NSOperation subclass loses NSOperation functionality

后端 未结 3 1493
攒了一身酷
攒了一身酷 2020-12-01 14:54

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

相关标签:
3条回答
  • 2020-12-01 15:32

    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")
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 15:48

    The problem is caused by this simple rule:

    Method in a generic class cannot be represented in Objective-C

    As a result, when bridged to Objective-C, MyOperation looks like pure, with no methods are overridden, NSOperation subclass.

    You can see this error by marking override func main() with @objc attribute.

    @objc override func main() {  // < [!] Method in a generic class cannot be represented in Objective-C
        println("My operation main was called")
    }
    
    0 讨论(0)
  • 2020-12-01 15:57

    In Xcode 7 generic NSOperation has been fixed: if I run this code in a playground it works:

    protocol SomeProtocol {
    
        // markup protocol
    }
    
    class GenericOperation<SomeTypeImplementingProtocol: SomeProtocol>: NSOperation {
    
        let referenceToSomeTypeImplementingProtocol: SomeTypeImplementingProtocol
    
        init(referenceToSomeTypeImplementingProtocol: SomeTypeImplementingProtocol) {
    
            self.referenceToSomeTypeImplementingProtocol = referenceToSomeTypeImplementingProtocol
        }
    
        override func main() {
    
            debugPrint("The GenericOperation main() method was called.")
    
        }
    }
    
    class TypeImplementingSomeProtocol: SomeProtocol {
    
    
        init() {
    
        }
    }
    
    
    let operationQueue = NSOperationQueue()
    
    let typeImplementingSomeProtocolInstance = TypeImplementingSomeProtocol()
    
    
    let operation = GenericOperation<TypeImplementingSomeProtocol>(referenceToSomeTypeImplementingProtocol: typeImplementingSomeProtocolInstance)
    
    
    operationQueue.addOperation(operation)
    
    0 讨论(0)
提交回复
热议问题