I'm writing a category for NSNotificationCenter
with a class method:
+(void)postNotificationName:(NSString*)name onMainThread:(BOOL)mainThread withObject:(id)object;
I'm doing this to make sure that I'm explicit with which thread my notifications are delivered, as this caused me a lot of hidden problems. And so just to avoid doing an extra look up every time I post a notification by calling [NSNotificationCenter defaultCenter]
every time, I thought I must just create a static variable once:
static NSNotificationCenter *defaultCenter;
+(void)postNotificationName:(NSString*)name onMainThread:(BOOL)mainThread withObject:(id)object
{
if(!defaultCenter)
defaultCenter = [NSNotificationCenter defaultCenter];
if(mainThread) {
dispatch_async(dispatch_get_main_queue(), ^{
[defaultCenter postNotificationName:name object:object];
});
} else {
[defaultCenter postNotificationName:name object:object];
}
}
Is what I'm doing safe? What if defaultCenter
is initially defined on a background thread and then used again on the main thread - is this asking for trouble? Is there a better way to do this?