我在一个应用程序中使用了多个视图控制器。在其中一个视图控制器上,观察者被初始化如下:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod:) name:@"MyNotification" object:nil];
即使在初始化NSNotification
之前删除它,myMethod:
的执行次数仍然会根据相应视图控制器上重复查看的数量进行累加。
为什么会发生这种情况,如何避免myMethod:
被调用多次。
注意:我通过使用断点确保没有多次调用postNotification
。
编辑:这是我的postNotification
的样子
NSArray * objects = [NSArray arrayWithObjects:[NSNumber numberWithInt:number],someText, nil];
NSArray * keys = [NSArray arrayWithObjects:@"Number",@"Text", nil];
NSDictionary * userInfo = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self userInfo:userInfo];
编辑:即使我把订阅移到viewWillAppear:之后,我仍然得到相同的结果。myMethod:被调用多次。(我重新加载视图控制器的次数)
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod:) name:@"MyNotification" object:nil];
}
编辑:我的生命周期好像有些问题。ViewDidUnload和dealloc没有被调用,但viewdiddisappear已经被调用。
我将我的ViewController推入堆栈的方式如下,其中父类是一个表视图子类(在单击行时初始化此viewController):
detailScreen * screen = [[detailScreen alloc] initWithContentID:ID andFullContentArray:fullContentIndex andParent:parent];
[self.navigationController pushViewController:screen animated:YES];
解决方案:
将nsnotification的移除操作移到viewdiddisappear中,这个方法很有效。感谢您的指导!
NSString * const ABCSomeNotification
两次... - Bert