我有一个SKScene,它使自己成为名为“showPhotoForMoodNotification”的通知的观察者,并具有名为"eventListenerDidReceiveNotification:“的关联选择器。
eventListenerDidReceiveNotification被声明为一个可以抛出和异常的函数,如下所示:
func eventListenerDidReceiveNotification(notif:NSNotification) throws { }但我注意到,当SKScene收到通知时,编译器不会将这个"eventListenerDidReceiveNotification“方法的签名与调用的addObserver中的”选择器“的签名关联起来,这看起来像thisL
NSNotificationCenter.defaultCenter().addObserver(self, selector: "eventListenerDidReceiveNotification:", name: "showPhotoForMoodNotification", object: nil)我得到的错误是:

因此,我猜测方法签名的“抛出”部分与nsnotification "addObserver“调用的”选择器“部分不兼容,因为如果我从"eventListenerDidReceiveNotification”方法声明中删除“抛出”部分,事情就会正常工作。
那么,我是否需要向addObserver“选择器”部分添加更多内容,才能将此方法描述为抛出异常的方法?
谢谢
发布于 2016-10-21 16:01:23
可能的答案是here。顺便说一句,在Swift 2.2中(实际上,我不知道你使用的是什么版本)中有new syntax for selectors,这是推荐的使用方式。(连接到情节提要中的按钮TouchUpInside事件的IBAction)
实际上,我刚刚测试了这段代码,它起作用了:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(test(_:)), name: "TestNotification", object: nil)
}
@objc private func test(notification: NSNotification) throws {
print("notification")
}
@IBAction private func fireNotification() {
NSNotificationCenter.defaultCenter().postNotificationName("TestNotification", object: nil)
}发布于 2016-10-21 16:08:26
IIRC,Swift方法,如
func f(x: T) throws -> U在目标C中被视为
- (nullable U *)fWithX:(T *)x error:(NSError **)errorPtr;因此,您可以尝试在选择器中添加该error:部件。
编辑:
和
func f() throws -> U变成了
- (nullable U *)fAndReturnError:(NSError **)errorPtr;https://stackoverflow.com/questions/38625525
复制相似问题