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
啊。那樣做了。奇怪 - 爲什麼不會有編譯時錯誤來捕捉錯誤? – DuckMaestro
因爲編譯器不能知道@selector(receiveNotification)不是你想要的。選擇器不是綁定到一個特定的類,因此據知道,其他類可能會實現它。或者你的類可以在其他編譯單元中實現它,甚至可以在運行時添加該方法。編譯器也不知道傳遞給'-addObserver:selector:name:object:'的觀察者應該實現選擇器參數 - Objective-C沒有提供任何方式告訴編譯器這種關係。 –