尝试侦听UIApplicationDidReceiveMemoryWarningNotification时“无法识别的选择器”

时间:2012-06-10 02:48:09

标签: objective-c ios nsnotificationcenter

我有一个类似“静态”的类,我希望能够响应低内存警告。但是,当我从模拟器手动触发低内存警告时,我收到“无法识别的选择器”错误。

相关代码:

@interface MyClass : NSObject
+ (void) receiveNotification:(NSNotification*) notification;
@end 

@implementation MyClass
+ (void) initialize {
    [super initialize];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification) name:@"UIApplicationDidReceiveMemoryWarningNotification" object:nil];
}
+ (void) receiveNotification:(NSNotification*) notification {
    // Breakpoint here never hits.
    // I instead receive error "+[MyClass receiveNotification]: unrecognized selector sent to class".
}
@end

1 个答案:

答案 0 :(得分:2)

您的方法名称为receiveNotification:(请注意冒号是名称的一部分)

所以选择器应该是@selector(receiveNotification:)

编辑:同样,顺便说一句,我不会在类初始化程序中调用[super initialize]。类似地,您应该防止一个子类导致您编写的这个初始化程序被调用两次。请参阅Mike Ash的这篇非常好的文章,了解更多信息:class loading and initialization

我希望有所帮助。