Giving notification to another class with NSNotificationCenter

拟墨画扇 提交于 2019-12-01 07:09:17

问题


So my goal is to deliver a notification to another class with using NSNotificationCenter, I also want to pass object with the notification to the other class, how should I do this?


回答1:


You must first register a notification name

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocating:) name:@"ForceUpdateLocation" object:nil]; // don't forget the ":"

And then post a notification with a dictionary of parameters

[[NSNotificationCenter defaultCenter] postNotificationName:@"ForceUpdateLocation" object:self userInfo:[NSDictionary dictionaryWithObject:@"1,2,3,4,5" forKey:@"categories_ids"]]; 

and the method will be

- (void)startLocating:(NSNotification *)notification {

    NSDictionary *dict = [notification userInfo];
}



回答2:


Just call any method for posting notifications as described here, for instance :

to post a notification :

-(void)postNotificationName:(NSString *)notificationName
                     object:(id)notificationSender
                   userInfo:(NSDictionary *)userInfo;

where userInfo is a dictionary containing useful objects.

On the other side to register for notifications :

-(void)addObserver:(id)notificationObserver
           selector:(SEL)notificationSelector
               name:(NSString *)notificationName
             object:(id)notificationSender;

You could also check Apple's Notification Programming Topics.



来源:https://stackoverflow.com/questions/6810105/giving-notification-to-another-class-with-nsnotificationcenter

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