类作为 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" );
}
Should it be possible to have a static NSNotification observer (like the code below)? I'm having some problems, and I think it may be due to my singleton class structure.
I don't always have a class instance around to listen to the notifications, but the static properties of this class stick around for my application's lifecycle.
- (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" );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个问题可能是你的选择器——应该是
@selector(action:)
。另外,您确定要在
init
中注册通知(缺少对[super init]
的任何调用,这可能是另一个问题)?这意味着每次您创建该类的实例时,您的通知都会被(重新)注册。您可能会考虑实现真正的单例对象而不是类方法。The first problem may be your selector — that should be
@selector(action:)
.Also, are you sure you want to register the notification in
init
(which is missing any call to[super init]
, which may be another problem)? That means your notification will be (re)registered every time you create an instance of the class. You might consider implementing a true singleton object instead of class methods.