NSNotifications in Swift 3

Are there new notifications that currently don't work in Swift 3? I do:

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

in the user view touchhesBegan (), and I need to send the particle object to the view controller, if any. So I do this:

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

in the controller view viewDidLoad (). I am sure that this particular view controller is the one that was presented when I clicked on my custom view, however the presentParticleDisplayView(notification:) function is never called.

In addition, DidTouchParticleView is defined globally as follows:

 let DidTouchParticleView = NSNotification.Name("didTouchParticleView") 

Is it because of the beta, or am I doing something wrong?

+7
ios swift3 beta nsnotification
source share
2 answers

It looks like you can call addObserver(_:selector:name:object:) , where the second parameter message ( selector: sent to the first parameter (target).

Instead, you call the wrong addObserver(forName:object:queue:using:) method, which works in a completely different way.

Also, regarding the second part of your question:

 let DidTouchParticleView = NSNotification.Name("didTouchParticleView") 

This is correct (almost); it should be

 let DidTouchParticleView = Notification.Name("didTouchParticleView") 

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

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

You can then reference the notification name as .didTouchParticleView to all of your code.

+11
source share

You yourself will follow the message ( object: self ). You probably mean the call to object: particle or perhaps object: nil in the addObserver call (but be careful to make sure that it is the right particle in the handler). Reread the documents for this method and carefully pay attention to the object parameter.

Note that this version of addObserver returns an observer object. You must save this so that later you can call removeObserver .

+1
source share

All Articles