gpt4 book ai didi

ios - removeObserver 不工作

转载 作者:可可西里 更新时间:2023-11-01 04:04:42 27 4
gpt4 key购买 nike

我有下一个代码:

@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]

此 VC 在开始时使用了一次 viewDidLoad,并且不能再次添加 Observer。

怎么了?

编辑我尝试将 addObserver 方法添加到 viewWillAppearviewWillDisappear - 没有结果。我在

之前添加 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 方法中运行 block

enter image description here

最佳答案

除了在其他答案中指出的添加/删除观察者调用未正确平衡外,还有另一个问题。

您删除观察者的代码是错误的。对于基于 block 的观察器,addObserver返回值 必须作为参数提供给removeObserver。所以你应该添加一个属性

@property(nonatomic, strong) id observer;

上课。然后你添加观察者

self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:NCDownloadComplete object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *n){
// ...
}];

并用

删除它
[[NSNotificationCenter defaultCenter] removeObserver:self.observer];

关于ios - removeObserver 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com