从通知中心删除Observer的最佳位置在哪里

时间:2013-11-12 16:34:01

标签: ios objective-c nsnotificationcenter

我认为应该在这里:

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc removeObserver:self];

}

或者可能在-dealloc

这两个听起来都很奇怪,所以我不完全确定它。

首先,在我的AppDelegate中,我通过Parse

收听远程通知
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [PFPush handlePush:userInfo];

    NSString * urlToGo = [userInfo objectForKey:@"url"];
    NSLog (@"Recibo notificación con paremetro url: %@", urlToGo);


    NSNotification *note = [NSNotification
                            notificationWithName:PUSH_NOTIFICATION
                            object:self
                            userInfo:userInfo];

    [[NSNotificationCenter defaultCenter] postNotification:note];

}

并在myViewController中      - (void)viewDidLoad {         [super viewDidLoad];

    _lastMenuSelected=menu1;

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [center addObserverForName:PUSH_NOTIFICATION
                        object:nil
                         queue:mainQueue
                    usingBlock:^(NSNotification *note) {

                     // Save in property to load parameter in prepareForSegure
                        _urlToLoadFromPush = urlToGoReceivedFromPush;
                    [self showPush:self];

                    }];


}



- (void)showPush:(id)sender {

    PushViewController * pushViewController=(PushViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"PushId"];

    pushViewController.url  = _urlToLoadFromPush;
    UINavigationController* nVC=[[UINavigationController alloc] initWithRootViewController:pushViewController];
    [self presentViewController:nVC animated:YES completion:^{
        //[_delegate logout];
    }];


}

2 个答案:

答案 0 :(得分:6)

由于您似乎在viewDidLoad方法中添加了观察者(从iOS 6开始仅调用一次),因此您应该使用dealloc方法删除观察者。

答案 1 :(得分:2)

请勿在viewWillDisappear中移除观察者,因为通常我们需要在视图位于堆栈中但不显示时发布通知。因此,总是尝试使用observer的名称删除 - (void)dealloc中的观察者。