我刚刚遇到了NSNotificationCenter
method[NSNotificationCenter defaultCenter] addObserverForName: object: queue: usingBlock:
方法,因为我开始习惯使用块,所以我决定尝试一下,因为这样可以提高代码的可读性。
但由于某种原因,我无法让它工作。为什么这不起作用
[[NSNotificationCenter defaultCenter] addObserverForName:@"SomeNotificationName"
object:self
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSLog(@"This doesn't work");
// ... want to do awesome stuff here...
}];
因为这工作得很好
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(aMethod)
name:@"SomeNotificationName"
object:nil];
//...
//....
- (void)aMethod {
NSLog(@"This works");
// ... doing awesome stuff here...
}
结束注
谢谢,以供将来参考,这是我的最终解决方案
// declared instance variable id _myObserver;
//...
_myObserver = [[NSNotificationCenter defaultCenter] addObserverForName:@"SomeNotificationName"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSLog(@"It's working! It's working!!");
// ... again doing awesome stuff here...
}];
最后,(当我完成对象时)
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:_myObserver];
}