Send and receive messages through NSNotificationCenter in Objective-C?

后端 未结 6 1491
感动是毒
感动是毒 2020-11-21 22:40

I am attempting to send and receive messages through NSNotificationCenter in Objective-C. However, I haven\'t been able to find any examples on how to do this.

6条回答
  •  心在旅途
    2020-11-21 23:02

    To expand upon dreamlax's example... If you want to send data along with the notification

    In posting code:

    NSDictionary *userInfo = 
    [NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
    [[NSNotificationCenter defaultCenter] postNotificationName: 
                           @"TestNotification" object:nil userInfo:userInfo];
    

    In observing code:

    - (void) receiveTestNotification:(NSNotification *) notification {
    
        NSDictionary *userInfo = notification.userInfo;
        MyObject *myObject = [userInfo objectForKey:@"someKey"];
    }
    

提交回复
热议问题