通用NSOperation子类失去NSOperation功能 [英] Generic NSOperation subclass loses NSOperation functionality

查看:116
本文介绍了通用NSOperation子类失去NSOperation功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



简单的例子:

  class MyOperation< T:NSObject>:NSOperation {

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

如果你创建这个类的一个实例并将它添加到 operationQueue 中,你会发现它是 main()实际上没有被调用。

 覆盖func viewDidLoad(){
super.viewDidLoad )
//加载视图后,通常从一个笔尖执行任何其他设置。

self.operationQueue = NSOperationQueue()
let operation = MyOperation< NSString>()
self.operationQueue!.addOperation(operation)
}

操作只需从准备好转换为执行完成状态而不调用 main()



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



这怎么可能?
我在这里丢失了什么?

解决方案

问题是由以下简单规则引起的:


通用类中的方法不能用Objective-C表示

因此,当桥接到Objective-C时, MyOperation 看起来像纯的,没有重写方法, NSOperation 通过用 @标记覆盖func main(),你可以看到这个错误。 objc 属性。

  @objc override func main(){//< [!]在一个泛型类中的方法不能用Objective-C 
println(My operation main was called)来表示
}


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?

解决方案

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

这篇关于通用NSOperation子类失去NSOperation功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆