我试图将对象从我的应用程序委托传递到另一个类的通知接收器。
我想传递整数messageTotal。现在我有:
messageTotal
在接收器中:
- (void) receiveTestNotification:(NSNotification *) notification { if ([[notification name] isEqualToString:@"TestNotification"]) NSLog (@"Successfully received the test notification!"); } - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissSheet) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"eRXReceived" object:nil];
在执行通知的类中:
[UIApplication sharedApplication].applicationIconBadgeNumber = messageTotal; [[NSNotificationCenter defaultCenter] postNotificationName:@"eRXReceived" object:self];
但是我想将对象传递messageTotal给另一个类。
您必须使用“ userInfo”变体,并传递一个包含messageTotal整数的NSDictionary对象:
NSDictionary* userInfo = @{@"total": @(messageTotal)}; NSNotificationCenter* nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];
在接收端,您可以按以下方式访问userInfo字典:
-(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); } }