有没有一种方法可以让一个对象在iPhone上发送一条没有特定接收者对象的消息,然后让另一个对象监听这些可能带有对象(参数)的消息,并执行所需的操作?
我搜索了NSNotification,但不知道该怎么办。
需要向通知中心注册以接收通知的对象。此后,当通知被张贴到通知中心时,通知中心将对照所有注册的过滤器进行检查,并对每个匹配的过滤器采取相应的操作。
在这种情况下,"过滤器"是(通知名称、通知对象)对。过滤器中的nil
对象等效于任何对象(匹配时忽略通知对象)。名称是必需的。
示例:
/* Subscribe to be sent -noteThis:
* whenever a notification named @"NotificationName" is posted to the center
* with any (or no) object. */
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(noteThis:)
name:@"NotificationName"
object:nil];
/* Post a notification. */
[nc postNotificationName:@"NotificationName" object:self userInfo:someDict];
/* Handle a notification. */
- (void)noteThis:(NSNotification *)note
{
id object = [note object];
NSDictionary *userInfo = [note userInfo];
/* take some action */
}
有一种更现代的API使用队列和块,但我发现旧的API更容易说明和解释。
基本上,您向共享类NSNotificationCenter
发布一个通知(NSNotification)。这里有一个例子:
#define kNotificationCenter [NSNotificationCenter defaultCenter]
#define kNotificationToSend @"a notification name as a string"
//... Post the notification
[kDefaultCenter postNotificationNamed:knotificationToSend withObject:nil];
任何想要侦听的类都会将自己作为观察者添加到通知中心。您还必须移除观察者。
[kNotificationCenter addObserver:self selector:@selector(methodToHandleNotification) object:nil];
//... Usually in the dealloc or willDisappear method:
[kNotificationCenter removeObserver:self];
您可以使用通知中心做更多的工作。请参阅NSNotificationCenter文档以获取完整参考。
我认为NSNotification
是消息对象本身,发送来监听发送的内容试试NSNotificationCenter
。它有一个singleton对象,所以要发送消息:
NSNotification *notificationObj;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotification:notificationObj];
另一个班听:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method:) object:nil];
请确保该类具有method:
方法。您可以有一个单独的参数,它是先前发送的NSNotification
对象。NSNotification
对象具有[notificationObj object
,您可以将其作为sender类发送的一段数据获取。或者,如果希望[notificationObj userInfo]
更结构化,也可以使用它。
您可以初始化notificationObj
并根据您想要的消息进行定制。更多关于NSNotificationCenter
的信息,你可以找到它
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/occ/cl/NSNotificationCenter
或有关CCD_ 12自身的更多信息
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html