2011-06-14 61 views
0

有没有一种方法可以将iPhone发送给没有特定接收器对象的对象发送消息,并进入另一个对象,收听此类消息与对象(参数),并做需要什么?iPhone - 发送消息“在空中”用于任何听众对象

我在NSNotification周围搜索,但我没有看到我应该做什么。

+0

你在运行相同的应用程序在两部手机之间是什么意思? – deanWombourne 2011-06-14 22:22:55

+0

@deanWombourne:不,我的意思是在一个应用程序内。发布编辑。 – Oliver 2011-06-14 22:23:56

回答

1

想要通知的对象需要注册才能收到通知中心的通知。之后,当通知被发布到通知中心时,通知中心将针对所有已注册的过滤器进行检查,并且将针对每个匹配过滤器采取相应的动作。

本例中的“过滤器”是一对(通知名称,通知对象)。过滤器中的对象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更易于说明和解释。

+0

非常感谢。非常有帮助 ! – Oliver 2011-06-14 22:40:42

1

基本上,您将通知(NSNotification)发布到共享类NSNotificationCenter。这里有一个例子:

#define kNotificationCenter [NSNotificationCenter defaultCenter] 
#define kNotificationToSend @"a notification name as a string" 

//... Post the notification 

[kDefaultCenter postNotificationNamed:knotificationToSend withObject:nil]; 

想要听任何类,增加了自身作为观察员到notifcation中心。你也必须删除观察者。

[kNotificationCenter addObserver:self selector:@selector(methodToHandleNotification) object:nil]; 

//... Usually in the dealloc or willDisappear method: 

[kNotificationCenter removeObserver:self]; 

您可以在通知中心做更多的事情。请参阅the NSNotificationCenter documentation fr完整参考。

+0

谢谢。我是在正确的方式。但是,如何将对象作为参数发送?应该听什么? – Oliver 2011-06-14 22:33:15

+0

监听对象只是一个过滤器,用于只监听给定的对象。如果您侦听一个零对象,则具有匹配名称的所有通知都将起作用。发布时,您可以发送一个对象和/或NSDictionary。查看更多文档。 – Moshe 2011-06-14 22:38:59

0

我认为NSNotification是消息对象本身,发送来听什么发送试试NSNotificationCenter。它有一个单独的对象,所以发送消息:

NSNotification *notificationObj; 
NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 
[center postNotification:notificationObj]; 

而另一类听搭配:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method:) object:nil]; 

确保类有method:方法。您可以拥有一个参数,即早期发送的NSNotification对象。 NSNotification对象具有[notificationObj object,您可以将其作为发件人类发送的一段数据获取。或者,如果您希望更具结构化,则可以使用[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