2012-06-10 45 views
1

我有一個「靜態」類,我希望能夠響應低內存警告。但是,當我從模擬器手動觸發低存儲器警告時,我收到「無法識別的選擇器」錯誤。嘗試偵聽UIApplicationDidReceiveMemoryWarningNotification時出現「無法識別的選擇器」

相關代碼:

@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 

回答

2

你的方法名是receiveNotification:(注意冒號是名稱的一部分)

所以選擇應該是@selector(receiveNotification:)

編輯:另外,順便說一句,我不會在類初始化器中調用[super initialize]。同樣,你應該防範一個子類,使你編寫的這個初始化器被調用兩次。看到這個從邁克灰非常好的帖子更多關於此:class loading and initialization

我希望有所幫助。

+0

啊。那樣做了。奇怪 - 爲什麼不會有編譯時錯誤來捕捉錯誤? – DuckMaestro

+2

因爲編譯器不能知道@selector(receiveNotification)不是你想要的。選擇器不是綁定到一個特定的類,因此據知道,其他類可能會實現它。或者你的類可以在其他編譯單元中實現它,甚至可以在運行時添加該方法。編譯器也不知道傳遞給'-addObserver:selector:name:object:'的觀察者應該實現選擇器參數 - Objective-C沒有提供任何方式告訴編譯器這種關係。 –

相關問題