Limit NSNotifications to Notify Within NSBundle Instances Only

×

This post was originally published in 2012
It may contain stale & outdated information. Or it may have grown more awesome with age, like the author.

NSNotifications are wonderful. So long as when using them within an NSBundle, one keeps the fact that notifications are broadcast to all instances of the bundle in mind.

To limit certain notifications to be bundle instance specific, one could append a unique id to each notification name.

For notifications sent and received by one class, this is trivial:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (id) initWithRepresentedObject:(id)inObject {
	self = [super initWithNibName:@"COIMMContentView" bundle:[COIMMPlugin bundle]];
 
	if (self) {
		[self setRepresentedObject:inObject];
                optionsController = [[COIMMOptionsController alloc] init];
                uniqueNotificationId = [[NSProcessInfo processInfo] globallyUniqueString];
 
                NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
 
                [notificationCenter addObserver:self
                           selector:@selector(rwDocumentDidAddPages:)
                               name:[kCOIMMRWDocumentDidAddPagesNotification stringByAppendingString:uniqueNotificationId]
                             object:nil];
 
                [notificationCenter addObserver:self
                           selector:@selector(rwDocumentDidRemovePages:) 
                               name:[kCOIMMRWDocumentDidRemovePagesNotification stringByAppendingString:uniqueNotificationId]
                             object:nil];
	}
 
	return self;
}

This implementation would not be ideal for cases where notifications are intended to be sent and received by different classes, but for my immediate use case, it works.

Comments (2) | Trackback