5

是否可以有一个静态的 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" );
}
4

1 回答 1

9

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

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

于 2010-12-08T02:14:22.637 回答