I have the following code in a Cocoa application:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSArray* arrayAppList = [[NSWorkspace sharedWorkspace] runningApplications];
}
My intention is to use KVO to detect an application when changes its state between inactive to active.
I read that I have to use the instance method -addObserver:forKeyPath:options:context:
And then use -observeValueForKeyPath:ofObject:change:context:
to respond to change notifications.
I understand that -observeValueForKeyPath
is a callback method where I can write code to respond to the properties changes I am interested in.
Nevertheless, I feel confused in how I must to use the addObserver method in order to be notified when the active
property of the runningApplications
change. Now, I am wondering where is the place to make the registration, for now I am using -applicationDidFinishLaunching
but not sure if is the right place to do it. Additionally if I use the -observeValueForKeyPath
callback method, I have to implement it in the class that inherits from NSObject
and is the same class where I am registering the notification?
You should call the
addObserver:…
method on each object in therunningApplications
array (usingisActive
as the key path).Starting the observing after your app finishes launching sounds about right. Time-wise, that is. As for the place, there should be a separate class dedicated to these observations. By implementing the observation code right in the app delegate you would violate the single-responsibility principle (and that means headache in the long term).
The
observeValueForKeyPath:…
callback should be implemented by the object that called theaddObserver:…
methods.