Swift 4-通知中心addObserver问题 [英] Swift 4 - Notification Center addObserver issue

查看:567
本文介绍了Swift 4-通知中心addObserver问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆