简介:我有一个发送通知的队列。视图控制器订阅它们,当它接收到它们时,它会显示一个图像。
问题:第一次,一切顺利。当我稍后回到视图时,我会看到收到通知但未显示图像的日志。
注意:后台线程是一个队列:dispatch_queue_create("scan", DISPATCH_QUEUE_SCAN)
,并从此队列发布通知。
@property(strong, nonatomic) id observer;
- (void)viewDidAppear:(BOOL) animated {
[super viewDidAppear:animated];
self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:MY_NOTIF object:nil queue:nil usingBlock:^(NSNotification *note) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"notification");
[self.img setImage:[UIImage imageNamed:@"register-ok"]];
[self.img setNeedsDisplay]; // useless
});
}
}
- (void)viewDidDisappear:(BOOL) animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:observer name:MY_NOTIF object:nil];
}
这真让我发疯。在此先感谢您的帮助
编辑:完成的更改:
NSLog(@"viewDidAppear. createObserver. self: %@");
[[NSNotificationCenter defaultCenter] addObserverForName:MY_NOTIF object:nil queue:nil usingBlock:^(NSNotification *note) {
NSLog(@"will call redraww. self: %@");
[self performSelectorOnMainThread:@selector(redraww:) withObject:nil waitUntilDone:YES];
}
-(void) redraww:(NSObject*)input {
NSLog(@"redraww self : %@", self);
[self.img setImage:[UIImage imageNamed:@"register-ok"]];
}
-(void) onRegistrationFinish {
NSLog(@"remove observer. self %@", self);
[[NSNotificationCenter defaultCenter] removeObserver:self name:(NSString *)NOTIF_SOLE_UUID object:nil];
}
控制台日志
viewDidAppear. createObserver self: <RegisterLeftViewController: 0x15e34550>
will call redraww. self:<RegisterLeftViewController: 0x15e34550>
redrawww self : <RegisterLeftViewController: 0x15e34550>
remove observer. self <RegisterLeftViewController: 0x15e34550>
************************* Second time
viewDidAppear. createObserver self: <RegisterLeftViewController: 0x15e98ba0>
will call redraww. self:<RegisterLeftViewController: 0x15e34550>
redrawww self : <RegisterLeftViewController: 0x15e34550>
remove observer. self <RegisterLeftViewController: 0x15e98ba0>
答案 0 :(得分:0)
好像你正在做一些可能导致麻烦的事情。
问题可能来自许多地方。以下是一些可以解决问题的方法:
__block __weak id observer
确保在通知处理程序中正确捕获自我。请参阅iOS NSNotificationCenter Observer not being removed 希望有所帮助