Ming Fan
Ming Fan

Reputation: 13

Better way to pass userInfo data with NSNotificationCenter in iOS

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

(or)

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

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

Which is better method from above two?

Upvotes: 0

Views: 670

Answers (4)

tounaobun
tounaobun

Reputation: 14857

postNotificationName:object: method invokes postNotificationName:object:userInfo: with a userInfo argument of nil.So basically there is no reason to argue with which one is better than the other.

Upvotes: 0

Wain
Wain

Reputation: 119031

Your first option abuses the 'sender' parameter of the notification because it's simple. It'll work, but it isn't correct. The idea with that parameter is that you can use it to filter the notifications that you receive. If you'll use it like that then fine, but it isn't for passing user info.

So, the second option is the correct one.

Imagine someone else coming to help on your project in the future - the more your code is written to follow standards the easier it'll be for them to help you.

Upvotes: 2

user212514
user212514

Reputation: 3130

The object parameter is the "notificationSender", that is, the object posting the notification. The userInfo parameter is intended to contain information about the the notification and it may be nil.

More details in Apple's reference documentation.

Upvotes: 0

Tyson Vignesh
Tyson Vignesh

Reputation: 315

In both the methods you are gonna get same output. you will fetch the object by notification.object. but in this,

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

there is no need to create a dictionary. it can reduce the code.

Upvotes: 0

Related Questions