我有下一个代码:
@implementation SplashViewVC
- (void)viewDidLoad
{
[super viewDidLoad];
self.splashView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default.png"]];
self.activityIndicator.originY = 355.f;
[[NSNotificationCenter defaultCenter] addObserverForName:NCDownloadComplete object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *n){
NSInteger errorCode = [n.userInfo[@"errorCode"] integerValue];
[self.activityIndicator stopAnimating];
if (errorCode == ERROR_CODE_NO_CONNECTION) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Some problem with server" delegate:self cancelButtonTitle:@"try again" otherButtonTitles:nil];
[alertView show];
} else if (errorCode == 0) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}];
[self downloadData];
}
- (void)downloadData
{
[self.activityIndicator startAnimating];
[[Server sharedServer] getMovieData];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[self downloadData];
}
- (void)viewDidDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super viewDidDisappear:animated];
}
@end
所以我把断点放在viewDidLoad
方法的开头,在viewDidDisappear
. 当我启动第一次转到的应用程序时viewDidload
,下载后转到viewDidDisappear
。
但是在我的应用程序中,我再次下载数据并发布notification: NSDownloadComplete
。在这个 VC 中它是有效的,但我后来删除了:
[[NSNotificationCenter defaultCenter] removeObserver:self]
这个VCviewDidLoad
一开始用过一次&不能再addObserver。
怎么了?
编辑
我尝试将 addObserver 方法放入viewWillAppear
或viewWillDisappear
- 没有结果。我NSLog(@"addObserver");
之前加
[[NSNotificationCenter defaultCenter] addObserverForName...
在 viewDidLoad
和写
- (void)viewDidDisappear:(BOOL)animated
{
NSLog(@"removeObserver");
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super viewDidDisappear:animated];
}
在日志中我看到:
2013-06-10 14:32:05.646 myApp[9390:c07] addObserver
2013-06-10 14:32:06.780 myApp[9390:c07] removeObserver
怎么了?
编辑 2 你可以看到必须删除观察者,但它再次在 addObserver 方法中运行块