venky
venky

Reputation: 1185

What is the use of Post NSNotification in ios?

I used NSNotification center for getting current volume of IPhone. example [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:MPMusicPlayerControllerVolumeDidChangeNotification object:musicPlayer]; i didnt use post Post notification in my code but volumeChanged method is called. so What is the use of Post Notification and how to use it?

Upvotes: 0

Views: 511

Answers (2)

ryan cumley
ryan cumley

Reputation: 1931

Many notifications are generated automatically by iOS and you are allowed to observe them and react accordingly, which is exactly what you've done by listening for the volume changed notification.

You are also free to post your own messages to the notification center, and other parts of your code may respond to them.

from within a method you may call something like this:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"com.ryan.cumley.updatedData" object:nil];

You can name the notification whatever you want, although to avoid conflicts you can use the com.xxx.xxx.whatever notation.

Now any object that currently exists in your app, which also previously added itself as an observer for this notification name will get this message and fire it's selector.

This design pattern is particularly useful for passing messages between distant objects without having to maintain any kind of clear reference to each other. Furthermore, many different objects can observe simultaneously, it's not just a 1-1 message.

You can also pass things with the notification by using that object: argument.

Upvotes: 1

Peter Warbo
Peter Warbo

Reputation: 11728

You are subscribing to the notification (so you don't have to send it). Probably MPMusicPlayerController is the class/instance sending the notification.

You can read more about how notifications work here.

Upvotes: 0

Related Questions