14

I'm building a program that launches another program and is then supposed to monitor it, and take action if it terminates. When the application is launched, I can get an instance of NSRunningApplication from NSWorkspace.

Now, the documentation states that NSRunningApplication has the property 'terminated' that is key-value observable. I've tried implementing:

[browserInstance addObserver:self 
                          forKeyPath:@"terminated"
                             options:NSKeyValueObservingOptionNew
                             context:NULL];

And:

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object 
                        change:(NSDictionary *)change
                       context:(void *)context  
{  

        NSLog(@"observeValueForKeyPath");  
        if ([keyPath isEqual:@"terminated"])  
        {  
            NSLog(@"terminated");  
        }  
} 

but I never see the observeValueForKeyPath method get tripped. Does anyone know how to make this work, if it is possible? I haven't been able to find any specific examples anywhere online.

Graham Miln
  • 2,724
  • 3
  • 33
  • 33
Iain Delaney
  • 562
  • 4
  • 17

4 Answers4

17

Have you tried the keyPath "isTerminated"?

Notice in the documentation for NSRunningApplication, the property terminated specifies the getter isTerminated, rather than the default getter terminated. (Which makes sense, as a Boolean property "is" or "isn't")

This suggests there may be a bug in obj-c property parsing, where the name of the getter is used for the KVO path.

bobDevil
  • 27,758
  • 3
  • 32
  • 30
4

I ended up using:

NSNotificationCenter *center = [[NSWorkspace sharedWorkspace] notificationCenter];

    // Install the notifications.

    [center addObserver:self 
               selector:@selector(appLaunched:) 
                   name:NSWorkspaceDidLaunchApplicationNotification 
                 object:nil];
    [center addObserver:self 
               selector:@selector(appTerminated:) 
                   name:NSWorkspaceDidTerminateApplicationNotification 
                 object:nil];

And then implementing the appLaunched and appTerminated methods.

Iain Delaney
  • 562
  • 4
  • 17
0

The “is it plugged in” question: You've verified that browserInstance is not nil, right?

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • I've stepped through the code a few times to make sure everything is set properly. I don't think there's an issue there. – Iain Delaney Nov 09 '10 at 13:58
0

Take a look at Apple's Technical Note 2050: Observing Process Lifetimes Without Polling.

TN2050 covers Apple's recommended methods for observing the lifetime of processes you launch, and those launched by others.

Robin Andersson
  • 5,150
  • 3
  • 25
  • 44
Graham Miln
  • 2,724
  • 3
  • 33
  • 33