Ation
Ation

Reputation: 731

Get notification's from NSNotificationServer in C++ program

I'm creating a simple C++ application with cmake on Mac. There is a main in C++ source code file, that create C++ class. Inside this class I'm allocating objective C object, that adding itself to observers in NSNotificationCenter. And I'm not receiving those notifications. There is a code:

Notifications.h

class LaunchNotification {
public:
    LaunchNotification();
    virtual ~LaunchNotification();

    void StartNotifications();
    void StopNotifications();

private:
    void    *monitor;
};

Notifications.mm

@interface Monitor : NSObject
-(id) init;
-(void) appLaunchedNotification :(NSNotification *) notification;
-(void) appTerminatedNotification :(NSNotification *) notification;
@end

@implementation Monitor

- (id) init
{
    self = [super init];
    if (self)
    {
        count = 0;
        NSNotificationCenter *notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];

        [notCenter addObserver : self
            selector:@selector(appLaunchedNotification:)
            name:NSWorkspaceDidLaunchApplicationNotification
            object:nil];

        [notCenter addObserver : self
            selector:@selector(appTerminatedNotification:)
            name:NSWorkspaceDidTerminateApplicationNotification
            object:nil];
    }

    return self;
}

- (void) appLaunchedNotification : (NSNotification *) notification
{
    NSString *path = [[notification userInfo]objectForKey: @"NSApplicationPath"];
}

- (void) appTerminatedNotification : (NSNotification *) notification
{
    NSString *path = [[notification userInfo]objectForKey: @"NSApplicationPath"];
}

- (void) dealloc
{
    NSNotificationCenter *notCenter = [[NSWorkspace sharedWorkspace] notificationCenter];

    [notCenter removeObserver : self];

    [super dealloc];
}
@end

LaunchNotification::LaunchNotification() : monitor(NULL)
{}

LaunchNotification::~LaunchNotification()
{
    StopNotifications();
}

void LaunchNotification::StartNotifications()
{
    if (NULL == monitor)
    {
        monitor = [[Monitor alloc] init];
    }
}

void LaunchNotification::StopNotifications()
{
    if (NULL != monitor)
    {
        [(id)monitor release];
    }
}

Upvotes: 0

Views: 788

Answers (1)

JeremyP
JeremyP

Reputation: 86651

You need a run loop because otherwise, NSWorkspace has no mechanism to gain control of your application's thread in order to post notifications.

While the docs say run loops are automatically created, they are not automatically executed. Think about it: how can a thread be simultaneously running your code and running the code in the run loop?

Any tasks that you need to do while you are monitoring the notification centre need to be done in the context of runloop events e.g. on an NSTimer event, or you need a separate thread for that other stuff.

Upvotes: 1

Related Questions