我想在NSNotification中将对象发送到选择器。我的意思是,我有3个按钮,点击每个按钮我正在注册通知,当该事件发生时,我正在调用一个选择器,在那个选择器中我想找出哪个按钮用户已单击,因为我对所有3个按钮都有共同的操作。
-(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.
}
我希望我很清楚。
答案 0 :(得分:4)
您可能需要查看NSNotificationCenter documentation
中的postNotificationName:object:userInfo:
您只需发送一个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 :(得分:0)
添加通知观察者时无法传递对象,因此您必须存储在某处按下的按钮:
-(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 )
...
}
答案 2 :(得分:-3)
以下代码段将为您提供帮助。
<强> Button1的强>
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur:) name:@"button1" object:button1];
<强>将Button2 强>
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur:) name:@"button2" object:button2];
将方法更改为以下
- (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");
}
}