我像这样在父类(super class) (UIViewController) 中注册接收通知:
SuperClass.m
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(notification:)
name:@"Notification"
object:nil];
}
- (void)notification:(NSNotification *)notification {
// Do something for SuperClass with the notification
}
现在在子类(SuperClass.m 的子类)中,我也像这样收听相同的通知:
子类.m
- (void)notification:(NSNotification *)notification {
// Do something specific for SubClass with the notification
}
这是一种可接受的(代码方式)方式来处理在父类(super class)中处理通知时的一般行为以及在子类中处理通知时处理更具体的行为吗?
最佳答案
通常,当您希望在子类中允许更具体的行为,同时仍保持父类(super class)中的一般行为时,您可以让子类调用 super
。例如,-[UIViewController viewDidAppear:]
文档说:
You can override this method to perform additional tasks associated with presenting the view. If you override this method, you must call
super
at some point in your implementation.
因此您的通知设置很好(尽管将 NSNotification
对象作为您希望被覆盖的方法的参数有点奇怪)——但您需要调用 [super notification:notification]
以获取父类(super class)的行为。
关于objective-c - 子类中的 NSNotificationCenter addObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13960943/