iPhone-向任何收听者对象“空中”发送消息

| iPhone上是否有一种方法可以让一个对象在没有特定接收方对象的情况下发送消息,并进入另一个对象,侦听此类可能随对象(参数)附带的消息,并且需要执行什么操作? 我搜索了NSNotification,但看不到该怎么办。     
已邀请:
        想要通知的对象需要在通知中心注册才能接收通知。此后,当通知发布到通知中心时,通知中心将对照所有已注册的过滤器对其进行检查,并对每个匹配的过滤器采取相应的措施。 在这种情况下,“过滤器”是一对(通知名称,通知对象)。过滤器中的“ 0”对象等效于任何对象(匹配时将忽略通知对象)。名称是必需的。 例:
/* 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更易于说明和解释。     
        基本上,您将通知(NSNotification)发布到共享类
NSNotificationCenter
。这是一个例子:
#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文档》完整参考。     
        我认为“ 5”是消息对象本身,要发送以收听发送的内容,请尝试“ 2”。它具有一个单例对象,因此要发送消息:
NSNotification *notificationObj;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotification:notificationObj];
另一类听:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method:) object:nil];
确保该类具有
method:
方法。您可以有一个参数,它是一个较早发送的“ 5”对象。
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 或有关
NSNotification
本身的更多信息 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html     

要回复问题请先登录注册