Skip to content

Instantly share code, notes, and snippets.

@Strilanc
Created November 21, 2013 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Strilanc/7585407 to your computer and use it in GitHub Desktop.
Save Strilanc/7585407 to your computer and use it in GitHub Desktop.
Code for NSNotificationCenter subscription controlled by cancellation token.
#import <XCTest/XCTest.h>
#import "TwistedoakCollapsingFutures.h"
#define notificationName @"note"
static int counter = 0;
@interface NSNotificationCenter (CancelToken)
-(void) addObserverForName:(NSString*)name
until:(TOCCancelToken*)untilCancelledToken
usingBlock:(void(^)(NSNotification*))block;
@end
@implementation NSNotificationCenter (CancelToken)
-(void) addObserverForName:(NSString*)name
until:(TOCCancelToken*)untilCancelledToken
usingBlock:(void(^)(NSNotification*))block {
id subscription = [self addObserverForName:name
object:nil
queue:nil
usingBlock:block];
[untilCancelledToken whenCancelledDo:^{
[self removeObserver:subscription];
}];
}
@end
@interface Attempt : NSObject
@property int localCounter;
@end
@implementation Attempt
@synthesize localCounter;
-(id)initUntil:(TOCCancelToken*)untilCancelledToken {
if (self = [super init]) {
NSNotificationCenter* c = NSNotificationCenter.defaultCenter;
[c addObserverForName:notificationName
until:untilCancelledToken
usingBlock:^(NSNotification *note) {
int oldCounterValue = counter;
counter++;
self.localCounter++;
NSAssert(counter==oldCounterValue+1, @"Atomicity guarantee violated.");
}];
}
return self;
}
@end
@interface Test2Tests : XCTestCase
@end
@implementation Test2Tests
-(void)testExample {
for(int i =0; i < 5; i++) {
TOCCancelTokenSource* c = [TOCCancelTokenSource new];
Attempt *a = [[Attempt alloc] initUntil:c.token];
[NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil];
[c cancel];
XCTAssertEqual(counter, i+1, @"Unexpected value for counter.");
XCTAssertEqual(1, a.localCounter, @"Unexpected value for localCounter.");
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment