2012-06-29 43 views
9

我有以下代碼:NSNotificationCenter一個帖子引起觀察者被調用兩次

[[NSNotificationCenter defaultCenter] postNotificationName:kNewsfeedFetchCompleted object:self userInfo:userinfo]; 

只有如此,沒有哪個地方。這裏就是我如何設置觀察:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsfeedFetchCompleted:) name:kNewsfeedFetchCompleted object:nil]; 

的問題是,當我做一個崗位newsfeedFetchCompleted調用兩次..這怎麼可能?

+0

[[NSNotification defaultCenter] removeObserver:self] – janusbalatbat

+0

你是什麼意思?我甚至爲什麼要這樣做? – xonegirlz

+2

AddObserver可能會爲同一個對象多次調用,導致多個通知。你在哪裏調用addObserver? –

回答

23

當您的addObserver代碼執行兩次時,這是可能的。通知功能將被註冊多次。

因此,確保您的代碼添加觀察員只執行一次。所以,你可以保持它在viewDidLoad或init方法。

如果你把它放在viewWillAppear中,那麼在viewWillDisAppear中移除觀察者。

+0

我實際上在initWithNib名稱中添加了這個名字 – xonegirlz

+0

在這種情況下,當您釋放該viewcontroller時,您錯過了removeallserver的dealloc方法。 – Apurv

+0

因此,如果第二次創建視圖控制器,您的觀察者將被重新註冊並且該函數將被調用兩次。 – Apurv

2

如果您爲newsfeedFetchCompleted通知添加了多次相同的觀察者,則可能會發生這種情況。您應該將addObserver調用與removeObserver調用相匹配。

例如,如果您在UIViewController的viewWillAppear/viewWillDidAppear/ViewDidLoad中添加了觀察者,則應該在viewWillDisappear/viewDidDisappear/ViewDidUnload中將其刪除。

相應刪除呼籲的addObserver,是removeObserver:name:object:

更多信息可以在NSNotificationCenter docs

8

找到您添加的觀察者之前,請確保您刪除以前的觀察員補充。

[[NSNotificationCenter defaultCenter]removeObserver:self]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newsfeedFetchCompleted:) name:kNewsfeedFetchCompleted object:nil]; 
+1

這應該有更多的票。真的幫我解決了一個問題,我的方法被調用了太多次。 –

相關問題