tags:

views:

377

answers:

4

Example: When memory gets low, the System sends an UIApplicationDidReceiveMemoryWarningNotification notification. That's all apple says in his doc at that point. But where does this notification come from, and to which method is it sent? Or where and how do I register what that I get notified?

+4  A: 

It is sent to the notification center, where all notifications are centralized. An object that wants to get informed about this notification registers itself to the notification center by telling which notification it wants to get informed and which method should be invoqued when the notification is raised.

For more information you can take a look to Notification programming topics for Cocoa and NSNotification class reference .

mouviciel
+3  A: 

From within the initialization code of the class you wish to receive the notification make the following method call:

[notificationCenter addObserver:self selector:@selector(handleMemoryWarning) name: UIApplicationDidReceiveMemoryWarningNotification object:nil];

This assumes that your class also implements a handleMemoryWarning method as follows:

- (void) handleMemoryWarning:(NSNotification *)notification
{
}
m4rkk
Don't forget to call removeObserver in that class's dealloc.
Abizern
Can't edit. Selector should be @selector(handleMemoryWarning:)
DougW
+4  A: 

Much simpler to use the application delegate and implement the optional method

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application

Most common notifications are also available translated into calls to a delegate, typically to optional methods in a formal protocol. Your delegate can be whatever object you like.

Jim
Note how you get the delegate name by taking the name of the notification and removing the `UI` from the beginning, `Notification` from the end and downcasing the first letter.
Abizern
A: 

Be warned that your selector will need to take the notification as an argument.

If you use something like @selector(handleMemoryWarning) and - (void) handleMemoryWarning { } the object WILL NOT send the notification and you'll still be holding onto all of your memory.

I was just bitten by this.

Ben Jackson