问题
I've a class called AppController.h/m I want to make something when the NSNotificationDidResignActiveNotification is sent. So i wrote this code in AppController.m:
-(void) initialize(){
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidResignActive:)
name:NSApplicationDidResignActiveNotification
object:nil ];
}
and then
-(void) applicationDidResignActive (NSNotification*) note{
NSBeep();
}
The problem is that the method isn't executed and i get this in the Console:
+[AppController applicationDidResignActive:]: unrecognized selector sent to class 0x61c4
I can't get where the problem is: could you help me?
Thank you!
回答1:
initialize
is a class method, not an instance method. I don't know this for sure, but it seems that when using a selector in a class method, it also assumes that selector will be a class method (for good reason). AppController has an instance method called applicationDidResignActive
, but not a class method named as such.
Instead of registering for notifications in +initialize
, override -init
and register there.
- (void)init
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidResignActive:)
name:NSApplicationDidResignActiveNotification
object:nil ];
}
来源:https://stackoverflow.com/questions/5173452/obj-c-cocoa-notification-nsapplicationdidresignactivenotification