对不从 Objective-C class 继承的 Swift class 使用 @objc 属性
Using @objc attribute for a Swift class that doesn’t inherit from an Objective-C class
Using Swift with Cocoa and Objective-C (Swift 2.1) documentation 的互操作性部分的以下段落似乎表明有一种方法可以使用不继承自 [=27] 的 Swift class =] class 互操作性。
When you create a Swift class that descends from an Objective-C class, the class and its members—properties, methods, subscripts, and initializers that are compatible with Objective-C—are automatically available from Objective-C. In some cases, you need finer grained control over how your Swift API is exposed to Objective-C. You can use the @objc attribute if your Swift class doesn’t inherit from an Objective-C class, or if you want to change the name of a symbol in your interface as it’s exposed to Objective-C code.
我尝试了以下操作:
import Foundation
@objc class FooBar {
@objc var name: String;
init() {
name = "Hello World!"
}
}
但不幸的是,它给出了编译错误:Only classes that inherit from NSObject can be declared @objc
我是不是误解了什么?
在 Apple 开发者论坛上查看此 thread。
基本上你说的在 Xcode <=6 是可能的,但在 Xcode 7
就被删除了
Pretty much yes. @objc
on Swift-rooted classes never quite behaved like an NSObject
-rooted class, leading to various weirdness in the generated header and at runtime. You can still treat any Swift class instance as an AnyObject
, mark methods and properties on a Swift class as @objc
, and conform to Objective-C protocols; the class just isn't exposed in the generated header and doesn't default to having its members available in Objective-C.
Using Swift with Cocoa and Objective-C (Swift 2.1) documentation 的互操作性部分的以下段落似乎表明有一种方法可以使用不继承自 [=27] 的 Swift class =] class 互操作性。
When you create a Swift class that descends from an Objective-C class, the class and its members—properties, methods, subscripts, and initializers that are compatible with Objective-C—are automatically available from Objective-C. In some cases, you need finer grained control over how your Swift API is exposed to Objective-C. You can use the @objc attribute if your Swift class doesn’t inherit from an Objective-C class, or if you want to change the name of a symbol in your interface as it’s exposed to Objective-C code.
我尝试了以下操作:
import Foundation
@objc class FooBar {
@objc var name: String;
init() {
name = "Hello World!"
}
}
但不幸的是,它给出了编译错误:Only classes that inherit from NSObject can be declared @objc
我是不是误解了什么?
在 Apple 开发者论坛上查看此 thread。
基本上你说的在 Xcode <=6 是可能的,但在 Xcode 7
就被删除了Pretty much yes.
@objc
on Swift-rooted classes never quite behaved like anNSObject
-rooted class, leading to various weirdness in the generated header and at runtime. You can still treat any Swift class instance as anAnyObject
, mark methods and properties on a Swift class as@objc
, and conform to Objective-C protocols; the class just isn't exposed in the generated header and doesn't default to having its members available in Objective-C.