Generic NSOperation subclass loses NSOperation functionality

99封情书 提交于 2019-11-27 08:44:51

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

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

}

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!