首页 文章

如何使用NSNotificationCenter传递对象

提问于
浏览
117

我试图将我的app委托中的对象传递给另一个类中的通知接收器 .

我想传递整数 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 传递给另一个类 .

4 回答

  • 25

    您必须使用“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);
        }
    }
    
  • 16

    在提供的解决方案的基础上,我认为显示一个传递您自己的自定义数据对象的示例可能会有所帮助(我在这里根据问题将其称为“消息”) .

    Class A (sender):

    YourDataObject *message = [[YourDataObject alloc] init];
    // set your message properties
    NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];
    

    Class B (receiver):

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [[NSNotificationCenter defaultCenter]
         addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
    }
    
    #pragma mark - Notification
    -(void) triggerAction:(NSNotification *) notification
    {
        NSDictionary *dict = notification.userInfo;
        YourDataObject *message = [dict valueForKey:@"message"];
        if (message != nil) {
            // do stuff here with your message data
        }
    }
    
  • 88

    Swift 2版本

    正如@Johan Karlsson指出的那样......我做错了 . 这是使用NSNotificationCenter发送和接收信息的正确方法 .

    首先,我们查看postNotificationName的初始化程序:

    init(name name: String,
       object object: AnyObject?,
     userInfo userInfo: [NSObject : AnyObject]?)
    

    source

    我们将使用 userInfo param传递我们的信息 . [NSObject : AnyObject] 类型是Objective-C的保留 . 因此,在Swift中,我们需要做的就是传入一个Swift字典,该字典包含从 NSObject 派生的键和可以 AnyObject 的值 .

    有了这些知识,我们就创建了一个字典,我们将其传递给 object 参数:

    var userInfo = [String:String]()
     userInfo["UserName"] = "Dan"
     userInfo["Something"] = "Could be any object including a custom Type."
    

    然后我们将字典传递给我们的对象参数 .

    Sender

    NSNotificationCenter.defaultCenter()
        .postNotificationName("myCustomId", object: nil, userInfo: userInfo)
    

    Receiver Class

    首先,我们需要确保我们的 class 正在观察通知

    override func viewDidLoad() {
        super.viewDidLoad()
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("btnClicked:"), name: "myCustomId", object: nil)   
    }
    

    然后我们可以收到我们的字典:

    func btnClicked(notification: NSNotification) {
       let userInfo : [String:String!] = notification.userInfo as! [String:String!]
       let name = userInfo["UserName"]
       print(name)
    }
    
  • 220

    斯威夫特4

    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"]
    }
    

    奖金(你绝对应该这样做!):

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

    extension Notification.Name {
        static let someNotificationName = Notification.Name("SomeNotificationName")
    }
    

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

    extension Notification.Key {
        static let key0 = "key0"
        static let key1 = "key1"
    }
    

    为什么我一定要这样做?为了避免代价高昂的拼写错误,享受重命名,享受使用等...

相关问题