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...
}
END NOTE
今後の参考のために、これが私の最終的な解決策です。
// 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];
}