在 iOS 中使用 NSNotificationCenter 传递 userInfo 数据的更好方法

Better way to pass userInfo data with NSNotificationCenter in iOS

[[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:self.productID];

(或)

NSDictionary *dict = @{@"productID":self.productID};

[[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:nil userInfo:dict];

以上两种方法哪个更好?

在这两种方法中,您将获得相同的输出。您将通过 notification.object 获取对象。 但在这方面,

[[NSNotificationCenter defaultCenter] postNotificationName:@"TapNewProduct" object:self.productID];

不需要创建字典。它可以减少代码。

object参数为"notificationSender",即发布通知的对象。 userInfo 参数旨在包含有关通知的信息,它可能为零。

More details in Apple's reference documentation.

您的第一个选项滥用了通知的 'sender' 参数,因为它很简单。它会工作,但它是不正确的。使用该参数的想法是您可以使用它来过滤您收到的通知。如果你会那样使用它,那很好,但它不是用来传递用户信息的。

所以,第二个选项是正确的。

想象一下,将来会有其他人来帮助您的项目 - 您编写的代码越符合标准,他们就越容易帮助您。

postNotificationName:object: 方法使用 nil 的 userInfo 参数调用 postNotificationName:object:userInfo:。所以基本上没有理由争论哪个比另一个更好。