Where and how do I register an object for receiving a Notification?

我只是一个虾纸丫 提交于 2019-12-22 06:23:08

问题


For example, when memory gets low, the System sends a UIApplicationDidReceiveMemoryWarningNotification notification. That's all Apple says in its docs 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?


回答1:


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 .




回答2:


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

[[NSNotificationCenter defaultCenter] 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
{
}



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/740562/where-and-how-do-i-register-an-object-for-receiving-a-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!