-1

I want to send object to selector in NSNotification.I mean, I have 3 buttons and on click of each button I am registering notification and when that event occurred I am calling one selector and in that selector I want to find out which button user has clicked because I have common action for all 3 buttons.

-(void)allThreeButtonAction:(sender)id
{
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur) name:@"EventCompletedNotification" object:nil];
}

//Some event occurred, so I am sending notification

[[NSNotificationCenter defaultCenter] postNotificationName:@"EventCompletedNotification" object:nil];

//Notified method

-(void)performSomeOperationWhenEventOccur
{
    //Here I want to know which button is pressed.
}

I hope I am clear.

4

3 回答 3

4

您可能想postNotificationName:object:userInfo:NSNotificationCenter 文档中查看

您只需发送一个 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];
于 2012-06-06T14:09:04.797 回答
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 )
        ...
}
于 2012-06-06T14:25:09.453 回答
-2

下面的代码片段将为您提供帮助。

按钮1

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur:) name:@"button1" object:button1];

按钮2

 [[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");
    } 
}
于 2012-06-06T14:18:14.987 回答