NSNotificationCenter userInfo

NSNotificationCenter userInfo

I must be pretty daft to nearly lose my mind every time I want to use NSNotificationCenter on the iPhone… for uses beyond a basic method call someplace in the wild. I want to send information. I am posting this only because when it’s been a while since I’ve used them, and I seem to forget what I am doing and end up figuring it out all over again. Each time. So this post is reference for me.

If you haven’t used them before, this may help you along. This doesn’t send an object along, but it could (just change the nil to something useful for you).

In a class that is doing the yelling:

NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys: yourStuff, nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@”someString” object:nil userInfo:dict];

In the class doing the listening:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod: ) name:@”someString” object:nil];

– (void)someMethod:(NSNotification *)notification {
NSDictionary *tmp = notification.userInfo;
//You could access notification.object here too
}

That’s about it really… stuff that userInfo with as much as you’d like within reason and have fun. NSNotificationCenter is really a fun way of yelling to whomever you want listening without worrying about scope. It’s quick and painless (unless like me – you had to track down using userInfo and/or object).

Happy Monday. Now, where is the nearest purveyor of hot liquid caffeine…

3 Replies to “NSNotificationCenter userInfo”

  1. Well, for one thing, I don’t need to create files to include – I just rely on NSNotificationCenter defaultCenter for picking up the slack for me. Most of the time my Classes folder is pretty well populated and it becomes a mess thinking about what is where, includes, etc.

    I think that custom delegates are certainly a great option. But when you want to be lazy, they are busy work. Just my opinion.

  2. And with notifications, it’s ‘one-to-many’ communication without any close binding that delegates imply: object A can tell anyone who’s interested that ‘X’ has happened, and doesn’t care if anyone’s listening, or thousands are listening. It’s the job of the intermediate notification center to care about that detail.
    –Anthony

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.