How to pass object with NSNotificationCenter

前端 未结 5 1143
广开言路
广开言路 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:28

    You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

    NSDictionary* userInfo = @{@"total": @(messageTotal)};
    
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];
    

    On the receiving end you can access the userInfo dictionary as follows:

    -(void) receiveTestNotification:(NSNotification*)notification
    {
        if ([notification.name isEqualToString:@"TestNotification"])
        {
            NSDictionary* userInfo = notification.userInfo;
            NSNumber* total = (NSNumber*)userInfo[@"total"];
            NSLog (@"Successfully received test notification! %i", total.intValue);
        }
    }
    

提交回复
热议问题