tmnd91
tmnd91

Reputation: 449

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!

Upvotes: 3

Views: 1962

Answers (1)

Mark Adams
Mark Adams

Reputation: 30846

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 ];
}

Upvotes: 3

Related Questions