【问题标题】:Swift 1.2 Why cannot I subclass any NSCell's subclass?Swift 1.2 为什么我不能继承任何 NSCell 的子类?
【发布时间】:2015-05-04 13:38:42
【问题描述】:

为什么我不能继承 NSCell 的任何子类? 我想继承MyButtonCell,即CustomButtonCell: NSButtonCell。意义

class MyCustomButtonCell: MyButtonCell { }

总是给我以下错误:

<unknown>:0: error: declaration has a different @objc name from the declaration it overrides ('initTextCell:' vs. 'initWithTextCell:')
Custom_Controls.MyButtonCell:9:24: note: overridden declaration is here
  @objc @objc override init(textCell aString: String)
                       ^
<unknown>:0: error: declaration has a different @objc name from the declaration it overrides ('initImageCell:' vs. 'initWithImageCell:')
Custom_Controls.MyButtonCell:10:24: note: overridden declaration is here
  @objc @objc override init(imageCell image: NSImage?)
                       ^

重现我的问题的简单步骤:

  1. 打开终端

  2. 输入:swift(如果你有最新的 Xcode 6.3.1)

  3. 当你得到时,

    Welcome to Swift version 1.2. Type :help for assistance.

输入以下内容:

1> import AppKit
2> class Foo : NSCell {}
3> class Bar : Foo {} 
  1. 您会收到以下错误:

declaration has a different @objc name from the declaration it overrides ('initTextCell:' vs. 'initWithTextCell:')__lldb_expr_9.Foo:3:24: note: overridden declaration is here @objc @objc override init(textCell aString: String) ^ declaration has a different @objc name from the declaration it overrides ('initImageCell:' vs. 'initWithImageCell:')__lldb_expr_9.Foo:4:24: note: overridden declaration is here @objc @objc override init(imageCell image: NSImage?) ^

为什么?有没有办法解决这个问题?

仅供参考:Swift 1.1 没有这个问题!

【问题讨论】:

  • 回答问题的“为什么”部分:NSCell 有两个初始化方法:initTextCell:initImageCell:。这些不遵循 Cocoa 命名约定,因为它们的名称中没有“with”。我认为这就是混淆 Swift 编译器的原因,它会打印出一些关于 initWithTextCell: 的内容。但我不知道为什么这只发生在子类中。

标签: objective-c macos swift nscell


【解决方案1】:

看来添加符合NSCoding的init方法可以消除错误:

import AppKit
class Foo : NSCell {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
class Bar : Foo {}

【讨论】:

  • 对我来说很好用!谢谢一堆。错误信息是如此误导我根本没有想到这一点。
猜你喜欢
  • 1970-01-01
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
相关资源
最近更新 更多