2011-06-03 80 views
0

我在確定如何分辨哪個對象發佈的通知的麻煩。確定哪個對象發佈通知?

予訂閱通知在對象A

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedNotification:) [email protected]"ReceivedData" object:nil] 

我發佈通知從對象B

[[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedData" object: self userInfo: dict]; 

我收到該通知中對象A

- (void) receivedNotification: (NSNotification*) notification 
{ 
    // Method is hit fine, notification object contains data. 
} 

我怎麼能知道它是對象B發送的數據而不是,例如,一個對象C?我需要對發件人的引用。我不想將發件人添加到正在傳遞的通知對象,因爲我在撥打對象時指定發件人B

回答

3

NSNotification的類有一個名爲object方法返回與所述通知相關聯的對象。這通常是發佈此通知的對象。

- (void) receivedNotification: (NSNotification*) notification 
{ 
    ... 
    id myObject = [notification object]; 
    ... 
} 
+0

這正是我想要檢索的內容。我如何在通知的接收者中獲得該信息?你可以看到我的問題,發佈通知的類包括object:self。 – 2011-06-03 16:51:09

+0

在通知參數上調用'object'方法。 – albertamg 2011-06-03 16:53:51

0

如果您只想處理來自B類的通知,則指定隨着對象(你已經離開爲nil)訂閱該通知時。

隨着nil,您從發佈的具體通知所有對象接收通知。

編輯

你叫[notification object]知道什麼對象張貼的通知。

+0

我不想僅限於B類的通知,我想確定通知的發件人。它來自哪裏並不重要。我只需要對該對象的引用。我計劃從通知中釋放對象。 – 2011-06-03 16:46:57

+0

更新我的問題 - 使用術語類不清楚。 – 2011-06-03 16:48:38

+0

我已經更新了我的答案。 – Abizern 2011-06-03 16:49:11