When you post a notification, it will cause all register observers to be notified. They get notified by having a message sent to them... the one identified by the selector. As mentioned in the comments, you should not use viewDidLoad
. Consider this...
- (void)newDataNotification:(NSNotification *notification) {
// Do whatever you want to do when new data has arrived.
}
In some early code (viewDidLoad is a good candidate):
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(newDataNotification:)
name:@"New data"
object:nil];
That's a terrible name, BTW. Oh well. This registration says that your self
object will be sent the message newDataNotification:
with a NSNotification
object whenever a notification is posted with the name "New data"
from any object. If you want to limit which object you want to receive the message from, provide a non-nil value.
Now, when you send the notification, you can do so simply, like you did in your code:
[[NSNotificationCenter defaultCenter] postNotificationName:@"New data" object:nil];
and that will make sure (for practical purposes) that [self newDataNotification:notification]
is called. Now, you can send data along with the notification as well. So, let's say that the new data is represented by newDataObject
. Since you accept notifications from any object, you could:
[[NSNotificationCenter defaultCenter]
postNotificationName:@"New data"
object:newDataObject];
and then in your handler:
- (void)newDataNotification:(NSNotification *notification) {
// Do whatever you want to do when new data has arrived.
// The new data is stored in the notification object
NewData *newDataObject = notification.object;
}
Or, you could pass the data in the user info dictionary.
[[NSNotificationCenter defaultCenter]
postNotificationName:@"New data"
object:nil
userInfo:@{
someKey : someData,
anotherKey : moreData,
}];
Then, your handler would look like this...
- (void)newDataNotification:(NSNotification *notification) {
// Do whatever you want to do when new data has arrived.
// The new data is stored in the notification user info
NSDictionary *newData = notification.userInfo;
}
Of course, you could do the same thing with the block API, which I prefer.
Anyway, note that you must remove your observer. If you have a viewDidUnload
you should put it in there. In addition, make sure it goes in the dealloc
as well:
- (void)dealloc {
// This will remove this object from all notifications
[[NSNotificationCenter defaultCenter] removeObserver:self];
}