Skip to content

Instantly share code, notes, and snippets.

@eralston
Created February 27, 2014 17:52
Show Gist options
  • Save eralston/9255255 to your computer and use it in GitHub Desktop.
Save eralston/9255255 to your computer and use it in GitHub Desktop.
A basic, block-oriented pub-sub pattern in Objective-C, demonstrating typedef of blocks and use of operation queues
//
// SimpleNotifier.h
//
#import <Foundation/Foundation.h>
typedef void (^VoidBlock)();
///
/// A simple notification to-many observers
///
@interface FRSNotifier : NSObject
-(id)init;
@property (nonatomic) NSOperationQueue *operationQueue;
-(id)addObserver:(VoidBlock)block;
-(void)removeObserver:(id)token;
-(void)postNotification;
@end
//
// SimpleNotifier.m
//
#import "SimpleNotifier.h"
@implementation SimpleNotifier
{
NSMutableDictionary *_observers;
}
///
/// Generates a new GUID
///
- (NSString *)uuidString {
// Returns a UUID
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
CFRelease(uuid);
return uuidString;
}
///
/// Default initializer that assigned a GUID as the notification ID
/// This enables code in the app to only worry about registering with the same object, rather than with the same ID
///
-(id)init
{
self = [super init];
if(self) {
_observers = [[NSMutableDictionary alloc] init];
}
return self;
}
///
/// Gets the operation queue used to call back observers of this object, returning the mainQueue by default
///
-(NSOperationQueue *)operationQueue
{
if(!_operationQueue) {
_operationQueue = [NSOperationQueue mainQueue];
}
return _operationQueue;
}
///
/// Adds an observing block of code to this notifier, which is called back when a notification is posted to this object
///
-(id)addObserver:(VoidBlock)block
{
NSString *token = [self uuidString];
[_observers setObject:block forKey:token];
return token;
}
///
/// Removes an observer with the given token from this notifier
///
-(void)removeObserver:(id)token
{
[_observers removeObjectForKey:token];
}
///
/// Posts a notification to the center for the current identifier
///
-(void)postNotification
{
NSOperationQueue *queue = self.operationQueue;
for (VoidBlock block in [_observers allValues]) {
[queue addOperationWithBlock:block];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment