2012-06-06 76 views
-1

我想送對象選擇在NSNotification.I的意思是,我有3個按鈕和每個按鈕的點擊我註冊的通知,並在該事件發生我打電話一個選擇,並在選擇我要找出哪個按鈕用戶點擊了,因爲我對所有3個按鈕都有共同的操作。如何在NSNotification中發送對象?

-(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. 
} 

我希望我很清楚。

回答

4

你可能想看看postNotificationName:object:userInfo:NSNotificationCenter documentation

您只需發送一個包含任何你需要確定按鈕的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]; 
+0

但如何我將在postNotificationName:object:userInfo中發送按鈕?我知道哪個按鈕只有當我註冊通知,在按鈕動作,即當我打電話時按下[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performSomeOperationWhenEventOccur :) name:@「EventCompletedNotification 「object:nil] ;. –

-2

下面摘錄會幫助你。

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"); 
    } 
} 
+0

感謝您的回覆,但我希望按鈕實例不僅是哪個按鈕被點擊的信息。 –

+1

如果你想通過按鈕對象,然後你爲什麼要傳遞對象:無通按鈕對象存在的nil.instead –

+0

看到我更新的答案 –

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) 
     ... 
}