2016-07-28 45 views
2

我有一个SKScene,它使用名为“eventListenerDidReceiveNotification:”的关联选择器使自己成为名为“showPhotoForMoodNotification”的通知的观察者。如何使用选择器:带有在Swfit中引发异常的函数

的eventListenerDidReceiveNotification被声明为可抛出和异常如下功能:

func eventListenerDidReceiveNotification(notif:NSNotification) throws { } 

但我注意到,当被SKScene收到通知,编译器不签名的此联营“ eventListenerDidReceiveNotification”方法与签名‘在选择的addObserver’叫,它看起来像thisL

NSNotificationCenter.defaultCenter().addObserver(self, selector: "eventListenerDidReceiveNotification:", name: "showPhotoForMoodNotification", object: nil) 

错误我得到的是这样的: enter image description here

所以,我的猜测是方法签名的“throws”部分与nsnotification“addObserver”调用的“selector”部分不兼容,因为如果我从“eventListenerDidReceiveNotification中消除”throws“部分“方法声明,事情工作。

所以,我必须添加任何更多的addObserver“选择器”部分来描述这种方法作为引发异常的方法吗?

感谢

回答

0

可能的答案here。顺便说一句,在Swift 2.2(实际上,我不知道你使用的是什么版本)有new syntax for selectors这是推荐使用它的方法。 (IBAction为连接到故事板按钮TouchUpInside事件)

事实上,我只是测试此代码和它的工作:

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

IIRC,夫特方法如

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;