Created
January 18, 2012 17:29
-
-
Save breeno/1634283 to your computer and use it in GitHub Desktop.
Simplifying NSNotificationCenter block based observers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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