Create a gist now

Instantly share code, notes, and snippets.

Spying on notifications.
#import <Cocoa/Cocoa.h>
// clang -Weverything -fobjc-arc -framework Cocoa -o notification notification.m
void QuietLog (NSString *format, ...);
void StartSpying (void);
void StopSpying (void);
void QuietLog (NSString *format, ...) {
va_list args;
va_start (args, format);
NSString *string;
string = [[NSString alloc] initWithFormat: format arguments: args];
va_end (args);
fprintf (stderr, "%s\n", [string UTF8String]);
} // QuietLog
NSMutableDictionary *g_notificationTokens;
void StartSpying (void) {
g_notificationTokens = [NSMutableDictionary dictionary];
id token;
NSNotificationCenter *center;
center = [NSNotificationCenter defaultCenter];
token = [center addObserverForName: nil
object: nil
queue: nil
usingBlock: ^(NSNotification *notification) {
QuietLog (@"NOTIFICATION %@ -> %@", notification.name, notification.userInfo);
}];
[g_notificationTokens setObject: token forKey: @"defaultCenter"];
[center removeObserver: token];
center = [NSDistributedNotificationCenter defaultCenter];
token = [center addObserverForName: nil
object: nil
queue: nil
usingBlock: ^(NSNotification *notification) {
QuietLog (@"DISTRIBUTED %@ -> %@", notification.name, notification.userInfo);
}];
[g_notificationTokens setObject: token forKey: @"distributedCenter"];
[center removeObserver: token];
center = [[NSWorkspace sharedWorkspace] notificationCenter];
// Hack to get the notification working with blocks
#ifndef RADAR_11827110
[center addObserver: @"hi"
selector: @selector(self)
name: nil
object: nil];
#endif
token = [center addObserverForName: nil
object: nil
queue: nil
usingBlock: ^(NSNotification *notification) {
QuietLog (@"WORKSPACE %@ -> %@", notification.name, notification.userInfo);
}];
[g_notificationTokens setObject: token forKey: @"workspaceCenter"];
} // StartSpying
void StopSpying (void) {
id token;
NSNotificationCenter *center;
token = [g_notificationTokens objectForKey: @"defaultCenter"];
center = [NSNotificationCenter defaultCenter];
[center removeObserver: token];
token = [g_notificationTokens objectForKey: @"distributedCenter"];
center = [NSDistributedNotificationCenter defaultCenter];
[center removeObserver: token];
token = [g_notificationTokens objectForKey: @"workspaceCenter"];
center = [[NSWorkspace sharedWorkspace] notificationCenter];
[center removeObserver: token];
} // StopSpying
int main (void) {
@autoreleasepool {
StartSpying ();
[[NSRunLoop currentRunLoop] run];
// Won't get called, but added for completeness.
StopSpying ();
}
return 0;
} // main
@joedevivo

This is great! It helped me quite a bit. Can you remember what the deal with the ifndef at line 55 is about?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment