Obj-C Cocoa Notification NSApplicationDidResignActiveNotification
Asked Answered
E

1

3

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!

Equestrian answered 2/3, 2011 at 21:3 Comment(1)
The Amazing Captain Pedanto says "technically, you don't have a class called AppController.h/m, you have a class called AppController with a header file AppController.h and an implementation file AppController.m. Hrumph."Designed
O
3

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 ];
}
Okelley answered 2/3, 2011 at 21:9 Comment(2)
thank you very much! It worked! So the problem was that the notification was sent to class and to istance, isnt'it?Equestrian
Exactly. That plus sign in the error message was the giveaway.Okelley

© 2022 - 2024 — McMap. All rights reserved.