Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-C Cocoa Notification NSApplicationDidResignActiveNotification

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!

like image 322
tmnd91 Avatar asked Dec 09 '25 13:12

tmnd91


1 Answers

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 ];
}
like image 112
Mark Adams Avatar answered Dec 13 '25 12:12

Mark Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!