如何使用 NSNotificationCenter 传递对象 [英] How to pass object with NSNotificationCenter
本文介绍了如何使用 NSNotificationCenter 传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一个对象从我的应用程序委托传递给另一个类中的通知接收器.
I am trying to pass an object from my app delegate to a notification receiver in another class.
我想传递整数messageTotal
.现在我有:
I want to pass integer messageTotal
. Right now I have:
在接收器中:
- (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
传递给另一个类.
But I want to pass the object messageTotal
to the other class.
推荐答案
您必须使用userInfo"变体并传递一个包含 messageTotal 整数的 NSDictionary 对象:
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];
在接收端,您可以按如下方式访问 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);
}
}
这篇关于如何使用 NSNotificationCenter 传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文