Obj-C Cocoa Notification NSApplicationDidResignActiveNotification

狂风中的少年 提交于 2019-12-11 01:34:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!