即使只添加一次观察者,通知也会被解雇两次

时间:2017-03-03 06:38:15

标签: ios objective-c nsnotificationcenter nsnotification

我有两个使用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__]}];
});

我还尝试了this solution EmptyStack,但没有让它发挥作用。

如果你能帮助我解决这个问题,我将非常感谢你。

感谢。

修改

注意

我在viewdidload中添加了观察者,并且无法从viewwillappera / viewwillappear或viewdidappear / viewdiddisappear添加/删除观察者,因为将在当前viewcontroller上推送的下一个viewcontroller将发布通知

2 个答案:

答案 0 :(得分:0)

我认为您需要在视图控制器中编写dealloc方法。并在dealloc方法

中删除所有通知观察者
- (void)dealloc
{
    // Deregister observer
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notification_deleteMediaFromGallery object:nil];
}

答案 1 :(得分:-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.