在哪里以及如何注册对象以接收通知?
例如,当内存不足时,系统会发送 UIApplicationDidReceiveMemoryWarningNotification
通知。 这就是苹果当时在其文档中所说的全部内容。 但是这个通知从哪里来,发送到哪个方法呢? 或者我在哪里以及如何注册我收到的通知?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从您希望接收通知的类的初始化代码中进行以下方法调用:
这假设您的类还实现了一个handleMemoryWarning方法,如下所示:
From within the initialization code of the class you wish to receive the notification make the following method call:
This assumes that your class also implements a handleMemoryWarning method as follows:
使用应用程序委托和实现可选方法要简单得多
大多数常见通知也可以转换为对委托的调用,通常是对正式协议中的可选方法的调用。 您的委托可以是您喜欢的任何对象。
Much simpler to use the application delegate and implement the optional method
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.
它被发送到通知中心,所有通知都集中在那里。 想要获得有关此通知的通知的对象通过告知它想要获得通知的通知以及在引发通知时应该调用哪个方法来将自己注册到通知中心。
有关更多信息,您可以查看 Cocoa 的通知编程主题 和 NSNotification 类参考。
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 .
请注意,您的选择器需要将通知作为参数。
如果您使用 @selector(handleMemoryWarning) 和 - (void) handleMemoryWarning { } 之类的东西,该对象将不会发送通知,并且您仍然会保留所有内存。
我刚刚被这个咬了。
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.