Iphone 如何在NSNotification中发送对象?
我想将对象发送到NSNotification中的选择器。我的意思是,我有3个按钮,在单击每个按钮时,我正在注册通知,当该事件发生时,我正在调用一个选择器,在该选择器中,我想找出用户单击了哪个按钮,因为我对所有3个按钮都有相同的操作Iphone 如何在NSNotification中发送对象?,iphone,objective-c,nsnotificationcenter,Iphone,Objective C,Nsnotificationcenter,我想将对象发送到NSNotification中的选择器。我的意思是,我有3个按钮,在单击每个按钮时,我正在注册通知,当该事件发生时,我正在调用一个选择器,在该选择器中,我想找出用户单击了哪个按钮,因为我对所有3个按钮都有相同的操作 -(void)allThreeButtonAction:(sender)id { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOpera
-(void)allThreeButtonAction:(sender)id
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur) name:@"EventCompletedNotification" object:nil];
}
//发生了一些事件,因此我正在发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"EventCompletedNotification" object:nil];
//通知方法
-(void)performSomeOperationWhenEventOccur
{
//Here I want to know which button is pressed.
}
我希望我说的很清楚。您可能想看看postNotificationName:object:userInfo:from
您只需发送一个UserInfo,其中包含标识按钮所需的任何内容,即指向您在选择器中检索的按钮的指针
您的选择器签名应收到通知:
- (void)performSomeOperationWhenEventOccur:(NSNotification*) notification:(NSNotification*) notification
{
// Use [notification userInfo] to determine which button was pressed...
}
注册选择器名称时,不要忘记修改它:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur:) name:@"EventCompletedNotification" object:nil];
下面的代码片段将帮助您 按钮1 按钮2 将方法更改为以下内容
添加通知观察者时无法传递对象,因此必须将按下的按钮存储在某个位置:
-(void)allThreeButtonAction:(id)sender
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur) name:@"EventCompletedNotification" object:nil];
self.buttonPressed = sender;
}
然后,您可以在通知处理程序中读取它:
-(void)performSomeOperationWhenEventOccur
{
if ( self.buttonPressed = self.button1 )
...
}
但我将如何在postNotificationName:object:userInfo中发送按钮?我知道只有在注册通知时,在按钮操作中,即当我调用[[NSNotificationCenter defaultCenter]addObserver:self selector:@selectorperformSomeOperationWhenEventOccur:name:@EventCompletedNotification object:nil];。谢谢你的回复,但我想要的不仅仅是按钮实例信息,还有点击哪个按钮。如果你想传递按钮对象,那么为什么要传递对象:nil。而不是nil pass button对象there@Downvoter如果你足够友善,请保持指出错误和建议正确解决方案的习惯。
- (void) performSomeOperationWhenEventOccur:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"button1"])
{
NSButton *button1=[notification button1];
NSLog (@"Successfully received the test notification! from button1");
}
else
{
NSButton *button2=[notification button2];
NSLog (@"Successfully received the test notification! from button2");
}
}
-(void)allThreeButtonAction:(id)sender
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur) name:@"EventCompletedNotification" object:nil];
self.buttonPressed = sender;
}
-(void)performSomeOperationWhenEventOccur
{
if ( self.buttonPressed = self.button1 )
...
}