Reputation: 1213
What is the usage of memory/processing that I'll have when use one:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dismissKeyboard) name:UIKeyboardWillHideNotification object:nil];
Or:
NSNotificationCenter * notificationCenter =
[notificationCenter addObserver:self selector:@selector(dismissKeyboard) name:UIKeyboardWillHideNotification object:nil];
PS: I think of to use NSNotificationCenter
to three different things. So my curiosity
Upvotes: 2
Views: 1086
Reputation: 299355
Your question is a little unclear. If you mean "how much time does it take to call [NSNotificationCenter defaultCenter]
?", don't worry about that. It's trivial. Usually people unload [NSNotificationCenter defaultCenter]
into a variable to save typing. I usually call the variable nc
because it's so long. The rest of this answer has to do with NSNotification
performance which may not be what you were asking.
Cocoa does not generally make promises about these things. You can't rely on the implementation details, and unfortunately, CFNotificationCenter
is not part of the open source version of Core Foundation, so you can't poke around and see how it's currently implemented.
But experience suggests (based on performance tuning I had to do a few years ago) that it's implemented as an array of observations. So it stores the observer, the selector, the name, and the object, which requires about 4x(pointersize) memory plus probably a ObjC structure overhead. So maybe 20-odd bytes or the like on a 64-bit platform.
addObserver
and removeObserver
were roughly equivalent to the cost of adding or removing an entry to an NSMutableArray
(in particular, removeObserver
is O(n) on the total number of observations registered with the center). Posting a notification is O(n) on the total number of observations registered with the center. (Again, this is based on reverse engineering; it could change over time, but I seriously doubt it. I'm sure this is very stable code by now.)
That means that NSNotification
does not scale well to thousands of observations. This is not to suggest that you should "avoid NSNotification
for performance reasons." (I hate when people say things like that without actually verifying it for their situation.) It just means that you need to be thoughtful before creating many hundreds or thousands of notifications in a system. That's what KVO is specifically designed for.
For your particular example, this is exactly what NSNotification
is designed for, so it's what you should use.
Upvotes: 7
Reputation: 11713
Objective-C is dynamic dispatch language. Which mean that message notification is at the core of Cocoa. You don't meet worry about how much memory is used. Just pay attention to fact that when you add an Observer, to make sure you remove them.
Upvotes: 1