2017-03-03 61 views
2

我有兩個類,它們使用NSNotification來相互通信。即使只添加觀察者一次也會發出兩次通知

目前,我有一個問題,通知被解僱兩次,我已經雙倍/三倍/甚至更多的檢查觀察員沒有被添加超過1次,通知沒有被髮布兩次,全球搜索我的項目相同通知。

我的代碼是像下面


新增通知觀察

[[NSNotificationCenter defaultCenter] removeObserver:self name:notification_deleteMediaFromGallery object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceiver:) name:notification_deleteMediaFromGallery object:nil]; 

通知接收器

- (void)notificationReceiver:(NSNotification*)notification { 
    if ([notification.name isEqualToString:notification_deleteMediaFromGallery]) { 
     if ([[notification.userInfo objectForKey:@"kind"] integerValue]==GalleryKindPhoto) { 
      //My statements 
     } 
     else if ([[notification.userInfo objectForKey:@"kind"] integerValue]==GalleryKindVideo) { 
      //My statements 
     } 
    } 
} 

郵政通知

dispatch_async(dispatch_get_main_queue(), ^{ 
    [_browser reloadData]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:notification_deleteMediaFromGallery object:nil userInfo:@{@"index":@(_browser.currentIndex), @"kind":@(self.kind), @"function":[NSString stringWithFormat:@"%s",__PRETTY_FUNCTION__]}]; 
}); 

我也通過EmptyStack試圖this solution但不能讓它開始工作。

如果你能幫我解決這個問題,我將非常感謝你。

感謝。

編輯

注意

我在我viewDidLoad中添加的觀察者,並不能從viewwillappera/viewWillAppear中添加/刪除觀察者或viewdidappear/viewdiddisappear因爲下一個視圖 - 控制將要上推當前viewcontroller會發布通知

+0

可以是U曾嘗試這一點,但你能告訴我們發生了什麼,你在這兩個地方增加一些打印語句之後;一個在哪裏你的帖子和一個你在哪裏註冊 – humblePilgrim

+0

@humblePilgrim是的我曾嘗試過,它記錄了一次我發佈我的通知,但在接收器中它記錄了兩次,地址號碼相同的通知 –

+0

我會在約一個小時內發佈通知日誌 –

回答

0

我認爲你需要在你的視圖控制器中寫入dealloc方法。並刪除所有通知觀察員dealloc方法,

- (void)dealloc 
{ 
    // Deregister observer 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notification_deleteMediaFromGallery object:nil]; 
} 
+0

嗯,感謝您的答覆,但我不認爲dealloc方法將被調用,因爲這些類是我的viewcontrollers,回彈將調用' - (void)viewWillDisappear :(BOOL)animated'和' - (void)viewDidDisappear:(BOOL)animated'。順便說一句,我在腦海裏有另一個提示,讓我試試看 –

+0

根據我的知識,你需要在ViewDidLoad()方法中添加addObserver,並在dealloc方法中刪除它。如果你想在viewDidDisappear中刪除,那麼你需要在viewWillappear方法中爲addObserver編寫代碼。 –

+0

沒有好友,我在我的'viewDidLoad'中添加了觀察者,並且我不能在'viewdiddisappear'中刪除觀察者,因爲下一個viewcontroller會發布通知。是的,dealloc方法永遠不會被調用,因爲dealloc被調用時,對象完全從內存中刪除,更多清除請[請查看此答案](http://stackoverflow.com/a/30332523/3308174) –

-2
Hi please make sure your method is not calling two time from where you are firing notification. 

& please add your notification observer in viewWillDisappear method. 
+0

請澄清您的回答 –

+0

現在用你自己的方法解決它:D – morroko

+0

沒問題好友,我會,可能現在或以後 –

相關問題