How to use KVO to detect when an application becomes active?

I have the following code in a Cocoa application:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSArray* arrayAppList = [[NSWorkspace sharedWorkspace] runningApplications]; } 

I intend to use KVO to detect the application when its state changes between inactive and active.

I read that I need to use the instance method -addObserver:forKeyPath:options:context:

And then use -observeValueForKeyPath:ofObject:change:context: to respond to notification of changes.

I understand that -observeValueForKeyPath is a callback method where I can write code to respond to changes in properties that interest me.

However, I am confused about how I should use the addObserver method to receive notifications when the active property changes runningApplications . Now I am wondering where is the place to register while I am using -applicationDidFinishLaunching , but not sure if this is the right place for this. Also, if I use the -observeValueForKeyPath callback method, should I implement it in a class that inherits from NSObject and is the same class where I register the notification?

+4
source share
1 answer
  • You must call the addObserver:… method for each object in the runningApplications array (using isActive as the path to the key).

  • Starting an observation after your application finishes launching sounds about the right. Temporarily, that is. As for the place, there should be a separate class dedicated to these observations. By injecting the observation code directly into the application delegate, you violate the principle of single responsibility (which means a headache in the long run).

  • The observeValueForKeyPath:… must be implemented by the object that called the addObserver:… methods.

+4
source

Source: https://habr.com/ru/post/1383725/


All Articles