objective-c - 如何使用 NSNotificationCenter 传递对象

标签 objective-c swift cocoa-touch nsnotificationcenter nsnotifications

我正在尝试将一个对象从我的应用委托(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/

相关文章:

ios - 将 View 高度约束覆盖为零时应用程序崩溃

objective-c - 更改 UIImage 的大小

ios - UIScrollViews 并在其上添加组件

objective-c - NSKeyedUnarchiver 不调用 initWithCoder

ios - 从 UITableView 中包含多个单元格的行中删除所选图像

ios - iOS 7开发人员-最小化应用会导致UIWebView嵌入式YouTube播放器停止播放

objective-c - "detailItem"和 "_detailitem"之间的区别

objective-c - 如何更改 Xcode 应用程序的外观?

ios - 标签栏 Controller 内的导航 Controller 不显示标题

ios - 如何使 UITextView 中的属性字符串可访问?