view raw
Youssef Sami Youssef Sami - 10 months ago 559
iOS Question

NSNotifications in Swift 3

Are the new notifications not currently working in Swift 3? I am doing:

NotificationCenter.default().post(name: DidTouchParticleView,
object: self.particle as? AnyObject)

in a custom view's touchesBegan() and I need to send the
object to the view controller if there is one. So I do this:

NotificationCenter.default().addObserver(forName: DidTouchParticleView,
object: self,
queue: OperationQueue.main(),
using: presentParticleDisplayView(notification:))

in a view controller's viewDidLoad(). I am certain that that particular view controller is the one presented when I tap my custom view, however, the function
is never called.

is defined globally like this:

let DidTouchParticleView = NSNotification.Name("didTouchParticleView")

Is this due to the beta, or am I doing something wrong?


It sounds like you may be intending to call addObserver(_:selector:name:object:), where the second parameter message (the selector:) is sent to the first parameter (the target).

Instead, you are calling the wrong method, addObserver(forName:object:queue:using:), which works quite differently.

Also, as to the second part of your question:

let DidTouchParticleView = NSNotification.Name("didTouchParticleView")

That is correct (almost); it should be

let DidTouchParticleView = Notification.Name("didTouchParticleView")

All notification names are now Notification.Name instances. The proper way to do this is to say:

extension Notification.Name {
    static let didTouchParticleView = Notification.Name("didTouchParticleView")

You can then refer to the notification's name as .didTouchParticleView throughout your code.