2017-10-11 114 views
3

每當Notification到達並且App嘗試執行其關聯方法時,我都會崩潰並收到unrecognized selector錯誤。 這裏是我的代碼 - 這是在viewDidLoadSwift 4 - 通知中心addObserver問題

let notificationCenter = NotificationCenter.default 
notificationCenter.addObserver(self, selector: Selector(("sayHello")), name:NSNotification.Name(rawValue: "dataDownloadCompleted"), object: nil) 

sayHello()方法很簡單 - 看起來是這樣的:

func sayHello() { 
    print("Hello") 
} 

我驗證過Notification成功發佈,它到達成功 - 所以這不是問題。當應用程序在Notification到達時採取行動 - 執行sayHello()方法時發生崩潰。它不斷給我,unrecognized selector錯誤。

任何想法我做錯了什麼? (順便說一句,這與Xcode 8完美配合,但現在Swift 4和Xcode 9的語法已經改變了[Xcode讓我通過必要的代碼修復/更新] - 但是崩潰仍在繼續。)

+0

如果您使用過'#selector',編譯器會指出問題 - 'sayHello'必須是'@ objc'。比較https://stackoverflow.com/q/44390378/2976878 – Hamish

+0

使用像這樣'#selector(yourVC.yourfunctionName)' – Mannopson

+0

正如@Hamish所提到的,你應該使用'#selector(sayHello)'和你的方法簽名也傳遞通知對象(放下NS前綴)'@objc func sayHello(_ notification:Notification)' –

回答

11

您可以通過以下步驟提高代碼:

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解決

+1

你應該放棄NS前綴 –

+0

是的,確切地說,謝謝;) –

+0

名稱不是通知的成員 - 問題快到4 –