objective-c - 分类为 NSNotification 观察者?

标签 objective-c cocoa nsnotifications nsnotificationcenter nsnotification

是否应该有一个静态的 NSNotification 观察器(如下面的代码)?我遇到了一些问题,我认为这可能是由于我的单例类结构所致。

我并不总是有类实例来收听通知,但此类的静态属性在我的应用程序的生命周期中一直存在。

- (id)init {
    [super init]

    [[NSNotificationCenter defaultCenter] addObserver:[self class]
                                             selector:@selector(action:aNotification:)
                                                 name:@"NSSomeNotification"
                                               object:nil];
    return self;
}

+ (void)action:(NSNotification *)aNotification {
    NSLog( @"Performing action" );
}

最佳答案

第一个问题可能是您的选择器 — 应该是 @selector(action:)

此外,您确定要在 init 中注册通知(缺少对 [super init] 的任何调用,这可能是另一个问题)?这意味着每次您创建该类的实例时,您的通知都会被(重新)注册。您可能会考虑实现真正的单例对象而不是类方法。

关于objective-c - 分类为 NSNotification 观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383478/

相关文章:

ios - 如何在 iOS 中缩放 UIScrollview 内部 Imageview?

ios - UITableViewCell 在第一次加载时无法正确呈现

objective-c - OSX 的 ASIHTTP 等效项

objective-c - objective-c 类和 swift 类之间的 NSNotification

ios - JWT 如何在 Smooch iOS 中工作?

iphone - postNotificationName : called 时未发送 NSNotification

objective-c - 取消dispatch_io_read

sql-server - 如何在 Mac 上连接到 Objective-C/Cocoa 中的 MS SQL Server?

swift - 在闭包中发布时未收到 NSNotificationCenter 通知

objective-c - 在应用程序准备使用(启动)之前调用 NSWorkspaceDidActivateApplicationNotification