如何使用NSNotificationCenter传递对象


129

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

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


Answers:


235

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

谢谢,我在messageTotalUIButton上设置了徽章,您知道如何用新的徽章计数刷新按钮吗?显示图像的代码viewDidLoadUIBarButtonItem *eRXButton = [BarButtonBadge barButtonWithImage:buttonImage badgeString:@"1" atRight:NO toTarget:self action:@selector(eRXButtonPressed)];
Jon

我不确定为什么您需要比较notification.name。名称的映射应在执行addObserver()时执行。仅在观察特定通知时才应调用receiveTestNotification。
约翰·卡尔森

1
Johan,在这种简单情况下,您是正确的,但是有可能有多个通知触发同一处理程序
Lytic

93

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

A类(发送者):

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

B类(接收器):

- (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
    }
}

2
为什么这个答案没有更多投票?!它运行完美,不是黑客!
Reuben Tanner 2014年

4
@Kairos,因为它并非设计为像这样使用。中的object参数postNotificationName 应表示发送此通知的参数。
xi.lin 2015年

2
是的,应该使用userInfo参数将对象作为NSDictionary传递,并且上面已接受的答案已经过编辑以显示出来。
大卫·道格拉斯

1
这是非常令人误解的,为什么这个答案会有这么多的反对?这应该删除。每个人都应该使用为此专门创建的userInfo。
Shinnyx

好的,谢谢您的反馈...我已经更新了答案,可以使用userInfo字典作为传递对象数据的方式。
大卫·道格拉斯

27

Swift 2版本

正如@约翰·卡尔森(Johan Karlsson)指出的那样……我做错了。这是使用NSNotificationCenter发送和接收信息的正确方法。

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

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

资源

我们将使用userInfo参数传递信息。该[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."

然后,将字典传递到对象参数中。

发件人

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

接收器类别

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

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)
}

您实际上违反了postNotificationName()的预期用途。但是你并不孤单。我已经看到许多开发人员使用object参数发送用户对象。第二个参数,对象,保留给发送者。您应该真正使用userInfo来发送所有类型的对象。否则,你可能会遇到随机崩溃等
约翰·卡尔松

25

斯威夫特5

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 {
  enum Key: String {
    case key0
    case key1
  }
}

我为什么一定要这样做?为避免代价高昂的拼写错误,请重命名,查找使用情况等。


谢谢。显然可以扩展Notification.Name,但不能扩展Notification.Key。 'Key' is not a member type of 'Notification'。参见此处:https
//ibb.co/hDQYbd2

谢谢,似乎Keystruct从那时起已被删除。我正在更新答案
星期五

1

Swift 5.1自定义对象/类型

// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
    static let yourNotificationName = Notification.Name("yourNotificationName")
}


// MARK: - CustomObject
class YourCustomObject {
    // Any stuffs you would like to set in your custom object as always.
    init() {}
}

// MARK: - Notification Sender Class
class NotificatioSenderClass {

     // Just grab the content of this function and put it to your function responsible for triggering a notification.
    func postNotification(){
        // Note: - This is the important part pass your object instance as object parameter.
        let yourObjectInstance = YourCustomObject()
        NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
    }
}

// MARK: -Notification  Receiver class
class NotificationReceiverClass: UIViewController {
    // MARK: - ViewController Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // Register your notification listener
        NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
    }

    // MARK: - Helpers
    @objc private func didReceiveNotificationWithCustomObject(notification: Notification){
        // Important: - Grab your custom object here by casting the notification object.
        guard let yourPassedObject = notification.object as? YourCustomObject else {return}
        // That's it now you can use your custom object
        //
        //

    }
      // MARK: - Deinit
  deinit {
      // Save your memory by releasing notification listener
      NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
    }




}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.