Ios 从通知中心移除观察员的最佳位置在哪里
我认为应该在这里:Ios 从通知中心移除观察员的最佳位置在哪里,ios,objective-c,nsnotificationcenter,Ios,Objective C,Nsnotificationcenter,我认为应该在这里: -(void) viewWillDisappear:(BOOL)animated { [super viewDidDisappear:animated]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self]; } 或者在-dealoc中 对我来说这两个听起来都很奇怪,所以我不能完全确定 首先,在我的AppDelegate
-(void) viewWillDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self];
}
或者在-dealoc
中
对我来说这两个听起来都很奇怪,所以我不能完全确定
首先,在我的AppDelegate中,我通过解析监听远程通知
- (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中
-(无效)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];
}];
}
因为您似乎要在
viewDidLoad
方法中添加观察者(从iOS 6开始只调用一次),您应该在dealloc
方法中删除观察者。不要在视图中删除观察者将消失,因为通常我们需要在视图位于堆栈中但未出现时发布通知。因此,请始终尝试在-(void)中删除观察者用观察者的名称解除锁定。你在哪里添加了观察者?从相反的方法中删除它。rmaddy是正确的,但如果你没有键入此代码作为示例,你将调用super ViewDidEverge from ViewWillEverge为什么在同一个文件中有应用程序委托和视图控制器的代码?或者发布的代码表单不同租赁类?如果是,请说明。好的,我已经编辑了帖子。要点是,它应该在后台和可见的两种情况下都做出反应,因为我们正在讨论推送通知,以及如果用户在使用应用程序时通知到达,则必须在解除分配视图控制器时将其删除,否则如果出现通知,您的应用程序将崩溃视图控制器消失后,会出现异常。