首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用NSNotificationCenter传递对象

如何使用NSNotificationCenter传递对象
EN

Stack Overflow用户
提问于 2011-10-26 06:27:55
回答 2查看 118.3K关注 0票数 135

我正在尝试将一个对象从我的应用程序委托传递到另一个类中的通知接收器。

我想要传递整数messageTotal。现在我有:

在接收器中:

代码语言:javascript
复制
- (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];

在执行通知的类中:

代码语言:javascript
复制
[UIApplication sharedApplication].applicationIconBadgeNumber = messageTotal;
[[NSNotificationCenter defaultCenter] postNotificationName:@"eRXReceived" object:self];

但是我想将对象messageTotal传递给另一个类。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-26 06:42:41

您必须使用"userInfo“变体并传递一个包含messageTotal整数的NSDictionary对象:

代码语言:javascript
复制
NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

在接收端,您可以访问userInfo字典,如下所示:

代码语言:javascript
复制
-(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);
    }
}
票数 239
EN

Stack Overflow用户

发布于 2016-12-29 00:31:15

Swift 5

代码语言:javascript
复制
func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

奖励(你绝对应该这么做!):

.someNotificationName替换Notification.Name("SomeNotificationName")

代码语言:javascript
复制
extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

"key0""key1"替换为Notification.Key.key0Notification.Key.key1

代码语言:javascript
复制
extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

为什么我一定要这么做呢?为了避免代价高昂的打字错误,享受重命名,享受查找用法等。

票数 33
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7896646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档