Skip to content

Instantly share code, notes, and snippets.

@bgulanowski
Created November 21, 2013 21:42
Show Gist options
  • Save bgulanowski/7590223 to your computer and use it in GitHub Desktop.
Save bgulanowski/7590223 to your computer and use it in GitHub Desktop.
How to use `-[NSNotificationCenter addObserverForName:object:queue:usingBlock:]`. Drop this in any Objective-C file of your choosing.
#import <libkern/OSAtomic.h>
static int32_t globalCounter;
@interface Test : NSObject
@property uint counter;
@property id observer;
@end
static NSLock *lock;
static NSOperationQueue *queue;
@implementation Test
+ (void)initialize {
if (self == [Test class]) {
queue = [[NSOperationQueue alloc] init];
[queue setName:@"Test"];
}
}
- (void)doTest
{
OSAtomicIncrement32(&globalCounter);
self.counter++;
NSLog(@"(%@) Global counter: %d; counter: %d", self, globalCounter, self.counter);
}
- (instancetype)init
{
self = [super init];
if (self) {
__weak Test *weakSelf = self;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
self.observer = [nc addObserverForName:@"TEST"
object:nil
queue:queue
usingBlock:^(NSNotification *note) {
[weakSelf doTest];
}];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self.observer];
NSLog(@"Goodbye from %@", self);
}
+ (void)runTest
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
for (NSUInteger i=0; i<5; ++i) {
Test *test = [[Test alloc] init];
[nc postNotificationName:@"TEST" object:nil];
NSLog(@"(LOOP) Global counter: %d; test counter: %d", globalCounter, test.counter);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment