Skip to content

Instantly share code, notes, and snippets.

@breeno
Created January 18, 2012 17:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save breeno/1634283 to your computer and use it in GitHub Desktop.
Save breeno/1634283 to your computer and use it in GitHub Desktop.
Simplifying NSNotificationCenter block based observers
#import <Foundation/Foundation.h>
@interface NSNotificationCenter (ObserverAdditions)
-(void) registerObserver: (id) observer
forName: (NSString *)name
object:(id)obj
queue:(NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *))block;
-(void) unregisterObserversForObserver: (id) observer;
@end
#import "NSNotificationCenter+ObserverAdditions.h"
#import <objc/runtime.h>
#define kNotificationObserversPaths @"__notificationObservers"
@interface NSObject(InternalRegisterObserverMethods)
-(NSMutableArray *) notificationObserversForObserver: (id) observer;
@end
@implementation NSNotificationCenter (ObserverAdditions)
-(void) registerObserver: (id) registeredObserver
forName: (NSString *)name
object: (id)obj
queue: (NSOperationQueue *)queue
usingBlock: (void (^)(NSNotification *note))block
{
id observer = [self addObserverForName: name object: obj queue: queue usingBlock: block];
[[self notificationObserversForObserver: registeredObserver] addObject: observer];
}
-(void) unregisterObserversForObserver: (id) registeredObserver;
{
for( id observer in [self notificationObserversForObserver: registeredObserver] )
{
[self removeObserver: observer];
}
}
#pragma mark- Internal Methods
-(NSMutableArray *) notificationObserversForObserver: (id) registeredObserver;
{
NSMutableArray *observed = objc_getAssociatedObject( registeredObserver, kNotificationObserversPaths);
if( !observed )
{
observed = [NSMutableArray array];
objc_setAssociatedObject( registeredObserver, kNotificationObserversPaths, observed, OBJC_ASSOCIATION_RETAIN);
}
return observed;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment