我正在尝试将一个对象从我的应用委托(delegate)传递给另一个类中的通知接收器。
我想传递整数 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);
}
}
关于objective-c - 如何使用 NSNotificationCenter 传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7896646/