作为NSNotification观察员的类?

Dov*_*Dov 5 cocoa objective-c nsnotifications nsnotification nsnotificationcenter

是否可以拥有静态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" );
}
Run Code Online (Sandbox Code Playgroud)

bos*_*acs 9

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

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