objective-c - 子类中的 NSNotificationCenter addObserver

标签 objective-c cocoa subclass superclass nsnotifications

我像这样在父类(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/

相关文章:

php - 多字符集替换算法

objective-c - 根据 AppleScript,Cocoa 应用程序不包含菜单栏

java - java中基于父类(super class)和子类对泛型类型的多重限制

iphone - +[NSInvocation invocationWithMethodSignature :]: method signature argument cannot be nil (Cocos2d)

ios - 获取 REST 数据的模式 "lazily"

swift - NSSearchField TextDidChange 的方法是什么?

cocoa - 编写安全的 Cocoa 代码

java - 创建一个包含方法的父类(super class)

swift - lineSpacing 是 UILabel 的属性吗?

javascript - 解析iOS SDK + 云代码: How to update user