简体   繁体   中英

NotificationCenter not working in didSelectRowAt in iOS Swift 3

Hello I wanna send notification to another view controller like this:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    NotificationCenter.default.post(name: Notification.Name("thisIsTestNotif"), object: nil)
}  

Thus set this in viewDidLoad:

NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)  

and in the following:

func thisistestHandler(notification:Notification)  {
}

but it does not work. The main problem is accrue when set call method in didSelectRow method.

Please help me to fix this problem.

The selector for your observer is wrong. Your notification observer method takes parameter, you have not specified that while adding observer for that method in the selector parameter. The fact that your project is compiling means there must be another method with the same name but with no parameters.

Change to:

override func viewDidLoad() {
    ............
    ............

    NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler(notification:)),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)
}

@objc func thisistestHandler(notification:Notification)  {

}

The most reliable – and ObjC compatible – Swift 3 syntax is

#selector(thisistestHandler(_:))

and

func thisistestHandler(_ notification: Notification)  {...

Of course the receiver of the notification must have been loaded already.


Note:

If the controllers are related then protocol / delegate or closure callback are the better choice. A Notification is supposed to be used only if there can be multiple receivers or sender and receiver are not related.

Instead of viewDidLoad

Add

NotificationCenter.default.addObserver(self,selector: #selector(thisistestHandler),name: NSNotification.Name(rawValue:"thisIsTestNotif"),object: nil)  

in viewWillAppear and remove observer in viewWillDisappear .

Just try not sure but might be work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM