Skip to content

Instantly share code, notes, and snippets.

@brackendev
Last active July 6, 2019 06:19
Show Gist options
  • Save brackendev/45ba13ca00aaf9616f778b5254b4c101 to your computer and use it in GitHub Desktop.
Save brackendev/45ba13ca00aaf9616f778b5254b4c101 to your computer and use it in GitHub Desktop.
[Objective-C] Unregistering block-based NotificationCenter observers using "Resource acquisition is initialization" (RAII)
//
// NotificationToken.h
//
// Created by brackendev
// Based on Ole Begemann's article and Swift implementation <https://oleb.net/blog/2018/01/notificationcenter-removeobserver/>
//
@import Foundation;
@interface NotificationToken : NSObject
- (instancetype)initWith:(NSNotificationCenter *)aNotificationCenter token:(id)aToken;
@end
//
// NotificationToken.m
//
// Created by brackendev
// Based on Ole Begemann's article and Swift implementation <https://oleb.net/blog/2018/01/notificationcenter-removeobserver/>
//
#import "NotificationToken.h"
@interface NotificationToken ()
@property (nonatomic, strong) NSNotificationCenter *notificationCenter;
@property (nonatomic) id token;
@end
@implementation NotificationToken
- (instancetype)initWith:(NSNotificationCenter *)aNotificationCenter token:(id)aToken {
self = [super init];
self.notificationCenter = aNotificationCenter;
self.token = aToken;
return self;
}
- (void)dealloc {
[self.notificationCenter removeObserver:self.token];
}
@end
//
// NSNotificationCenter+Token.h
//
// Created by brackendev
// Based on Ole Begemann's article and Swift implementation <https://oleb.net/blog/2018/01/notificationcenter-removeobserver/>
//
@import Foundation;
@class NotificationToken;
@interface NSNotificationCenter (Token)
- (NotificationToken *)observeForName:(NSNotificationName)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block;
@end
//
// NSNotificationCenter+Token.m
//
// Created by brackendev
// Based on Ole Begemann's article and Swift implementation <https://oleb.net/blog/2018/01/notificationcenter-removeobserver/>
//
#import "NSNotificationCenter+Token.h"
#import "NotificationToken.h"
@implementation NSNotificationCenter (Token)
- (NotificationToken *)observeForName:(NSNotificationName)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block {
id token = [self addObserverForName:name object:obj queue:queue usingBlock:block];
return [[NotificationToken alloc] initWith:self token:token];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment