通用NSOperation子类失去了NSOperation功能

Nev*_*s12 9 generics nsoperation nsoperationqueue swift

今天,当我试图"概括"我的'CoreData导入操作'时,我遇到了一个奇怪的问题.似乎如果我创建NSOperation的泛型子类,main()则不会调用func.

简单的例子:

class MyOperation<T: NSObject>: NSOperation {

    override func main() {
        println("My operation main was called")
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您创建此类的实例并将其添加到operationQueue您将看到它main()实际上没有被调用.

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)
}
Run Code Online (Sandbox Code Playgroud)

操作简单地从过境readyexecutingfinished状态,而无需调用main().

如果我<T: NSObject>MyOperation类中删除泛型注释,它将正常工作.

这怎么可能?我在这里错过了什么吗?

小智 12

解决方法:您可以创建NSOperation子类(不是通用的),覆盖main并调用您自己的'execute'func,它可以被泛型子类覆盖.例:

class SwiftOperation : NSOperation {

    final override func main() {
        execute()
    }

    func execute() {
    }

}

class MyOperation<T> : SwiftOperation {

    override func execute() {
        println("My operation main was called")
    }

}
Run Code Online (Sandbox Code Playgroud)


rin*_*aro 7

问题是由这个简单的规则引起的:

泛型类中的方法不能在Objective-C中表示

因此,当桥接到Objective-C时,MyOperation看起来像纯粹的,没有方法被重写,NSOperation子类.

您可以通过override func main()使用@objc属性标记来查看此错误.

@objc override func main() {  // < [!] Method in a generic class cannot be represented in Objective-C
    println("My operation main was called")
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的澄清.令人遗憾的是,我们不能在Swift中使用如此强大的技术与Objective-C.在这种特殊情况下,"通用"操作可以帮助重用相当多的代码.嗯,是的 :/ (2认同)