有没有一种方法可以将iPhone发送给没有特定接收器对象的对象发送消息,并进入另一个对象,收听此类消息与对象(参数),并做需要什么?iPhone - 发送消息“在空中”用于任何听众对象
我在NSNotification周围搜索,但我没有看到我应该做什么。
有没有一种方法可以将iPhone发送给没有特定接收器对象的对象发送消息,并进入另一个对象,收听此类消息与对象(参数),并做需要什么?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更易于说明和解释。
非常感谢。非常有帮助 ! – Oliver 2011-06-14 22:40:42
基本上,您将通知(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完整参考。
我认为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
更多信息,你可以找到它
或了解更多信息有关NSNotification
本身
你在运行相同的应用程序在两部手机之间是什么意思? – deanWombourne 2011-06-14 22:22:55
@deanWombourne:不,我的意思是在一个应用程序内。发布编辑。 – Oliver 2011-06-14 22:23:56