2010-08-11 129 views
0

有什么用NS通知在iphone sdk?NS通知iphone sdk

感谢

+0

可能[什么是NSNotification?](http://stackoverflow.com/questions/1900352/what-is-nsnotification) – 2010-09-19 22:35:27

回答

3

我知道这不是一般的回答问题的好办法,但RTFM

NSNotification对象封装信息,以便它可以通过NSNotificationCenter对象广播到其他对象。 NSNotification对象(称为通知)包含名称,对象和可选字典。该名称是标识通知的标签。该对象是通知的发布者想要发送给该通知的观察者的任何对象(通常是发布通知的对象)。该字典存储其他相关对象,如果有的话。 NSNotification对象是不可变的对象。

您可以使用类方法notificationWithName:object:或notificationWithName:object:userInfo:创建通知对象。但是,您通常不会直接创建自己的通知。 NSNotificationCenter方法postNotificationName:object:和postNotificationName:object:userInfo:允许您方便地发布通知,而无需先创建它。

0

在事件方面NSNotifications是委托的替代方案。可以使用委托来通知一个事件的单个代表,而通知可用于通知任意数量的接收器。通知被发送到主通知中心,然后通知所有已注册通知的对象。

一个重要的区别是,使用委托您可以接收委托人对事件的响应,而使用NSNotifications您只需发送通知,但您不知道接收者或他们对通知的响应。

0

当您想从iOS接收警报时,您注册了一个UINotification。因此,如果您想在插入配件或插入电视机时执行某些操作,则会为其注册一个UINotification,并在事件发生时调用应用程序中的方法。

1

NSNotifications允许您在事件发生时调用一个方法。 例如,如果你有一个MPMoviePlayer,你想待办事项的东西,当它完成后,你可以使用下面的代码:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:yourMoviePlayer.moviePlayer];

或者,如果你想要做的事,当设备旋转:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:self];