Swift 4-通知中心addObserver问题 [英] Swift 4 - Notification Center addObserver issue
问题描述
每次Notification
到达并且App尝试执行其关联的方法时,我都崩溃并收到unrecognized selector
错误.
这是我的代码-在viewDidLoad
中:
I'm crashing and getting an unrecognized selector
error every time a Notification
arrives and the App tries to execute its associated method.
Here's my code - which is in viewDidLoad
:
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: Selector(("sayHello")), name:NSNotification.Name(rawValue: "dataDownloadCompleted"), object: nil)
sayHello()
方法非常简单-看起来像这样:
The sayHello()
method is quite simple - looks like this:
func sayHello() {
print("Hello")
}
我已经确认Notification
已成功发布并且到达成功-但这不是问题.当App希望在Notification
到达时采取措施-通过执行sayHello()
方法来执行崩溃.它一直给我unrecognized selector
错误.
I've verified that the Notification
is posted successfully and that it arrives successfully - so that's not the issue. The crash happens when the App looks to act upon the arrival of the Notification
- by executing the sayHello()
method. It keeps giving me that unrecognized selector
error.
有什么主意我做错了吗? (顺便说一句,这与Swift 3和Xcode 8完美配合,但是现在与Swift 4和Xcode 9一起使用,语法已更改[Xcode引导我完成了必要的代码修复/更新]-但崩溃仍在继续.) >
Any ideas what I'm doing wrong? (By the way, this worked perfectly with Swift 3 & Xcode 8, but now with Swift 4 and Xcode 9 the syntax has changed [Xcode walked me through the necessary code fixes/updates] - but the crashes keep happening.)
推荐答案
您可以通过以下步骤改进代码:
You can improve your code with these steps:
extension Notification.Name {
static let dataDownloadCompleted = Notification.Name(
rawValue: "dataDownloadCompleted")
}
并像这样使用它:
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(YourClass.sayHello),
name: .dataDownloadCompleted,
object: nil)
但是正如已经指出的,通过更改为 #selector
But as was already pointed out, issue is solved by changing to #selector
这篇关于Swift 4-通知中心addObserver问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!