Search code examples
nsnotificationcentercore-foundation

App Changed Notifications in CFRunLoop Daemon


static void registerForDriverLoadedNotification()
{
    // Snipped code that works and is not related to issue
}

static void registerForApplicationChangedNotification()
{
    NSLog(@"registerForApplicationChangedNotification!");
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    [center addObserverForName: nil object: nil queue: nil
            usingBlock: ^(NSNotification* notification) {
                          NSLog(@"NOTIFICATION %@ -> %@", notification.name,
                                                          notification.userInfo);
                        }];
}


int main (int argc, const char* argv[]) {
    registerForDriverLoadedNotification();
    registerForApplicationChangedNotification();

    CFRunLoopRun();

    return 0;
}

The above code is for a daemon process, it waits for USB devices to be plugged in, then loads a configuration. I would like to extend this functionality to also detect when applications are launched, and if an app-specific config is present load it.

However, I do not seem to receive any notifications other than NSUserDefaultsDidChangeNotification.

The code above in registerForApplicationChangedNotification originally was monitoring both NSWorkspaceDidActivateApplicationNotification and NSWorkspaceDidDeactivateApplicationNotification, but I changed it to the catch-all so I could see what other notifications were being posted.

No matter what happens only the NSUserDefaultsDidChangeNotification notification seems to be received... what is wrong with this rather simple code?


Solution

  • Silly mistake!

    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];

    Should be:

    NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter]