How to pass object with NSNotificationCenter

前端 未结 5 1135
广开言路
广开言路 2020-11-28 18:42

I am trying to pass an object from my app delegate to a notification receiver in another class.

I want to pass integer messageTotal. Right now I have:<

5条回答
  •  感情败类
    2020-11-28 19:37

    Building on the solution provided I thought it might be helpful to show an example passing your own custom data object (which I've referenced here as 'message' as per question).

    Class A (sender):

    YourDataObject *message = [[YourDataObject alloc] init];
    // set your message properties
    NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];
    

    Class B (receiver):

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter]
         addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
    }
    
    #pragma mark - Notification
    -(void) triggerAction:(NSNotification *) notification
    {
        NSDictionary *dict = notification.userInfo;
        YourDataObject *message = [dict valueForKey:@"message"];
        if (message != nil) {
            // do stuff here with your message data
        }
    }
    

提交回复
热议问题