使用 Objective-C 选择器声明方法时出错
Error declaring method with Objective-C selector
我在尝试声明方法时遇到此错误:
代码如下:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("itemDroppedOnCharacter:"), name: "onTargetDropped", object: nil)
func itemDroppedOnCharacter(notif: AnyObject) {
print("Item Dropped On Character")
}
我做错了什么?
选择器在 Xcode 7.3 中发生了变化。您需要显式声明属于您的 class:
的选择器
class MyClass {
func someFunc() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyClass.itemDroppedOnCharacter(_:)), name: "onTargetDropped", object: nil)
}
@objc func itemDroppedOnCharacter(notif: AnyObject) {
print("Item Dropped On Character")
}
}
如果您不想添加 @objc
以将选择器暴露给 Objective-C:
,您也可以让 MyClass
继承自 NSObject
class MyClass: NSObject {
func someFunc() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyClass.itemDroppedOnCharacter(_:)), name: "onTargetDropped", object: nil)
}
func itemDroppedOnCharacter(notif: AnyObject) {
print("Item Dropped On Character")
}
}
我在尝试声明方法时遇到此错误:
代码如下:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("itemDroppedOnCharacter:"), name: "onTargetDropped", object: nil)
func itemDroppedOnCharacter(notif: AnyObject) {
print("Item Dropped On Character")
}
我做错了什么?
选择器在 Xcode 7.3 中发生了变化。您需要显式声明属于您的 class:
的选择器class MyClass {
func someFunc() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyClass.itemDroppedOnCharacter(_:)), name: "onTargetDropped", object: nil)
}
@objc func itemDroppedOnCharacter(notif: AnyObject) {
print("Item Dropped On Character")
}
}
如果您不想添加 @objc
以将选择器暴露给 Objective-C:
MyClass
继承自 NSObject
class MyClass: NSObject {
func someFunc() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyClass.itemDroppedOnCharacter(_:)), name: "onTargetDropped", object: nil)
}
func itemDroppedOnCharacter(notif: AnyObject) {
print("Item Dropped On Character")
}
}