如何使用 KVO 检测应用程序何时处于活动状态?
我在 Cocoa 应用程序中有以下代码:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSArray* arrayAppList = [[NSWorkspace sharedWorkspace] runningApplications];
}
我的目的是使用 KVO 来检测应用程序的状态从非活动状态更改为活动状态。
我读到我必须使用实例方法 -addObserver:forKeyPath:options:context:
然后使用 -observeValueForKeyPath:ofObject:change:context:
来响应更改通知。
我知道 -observeValueForKeyPath
是一种回调方法,我可以在其中编写代码来响应我感兴趣的属性更改。
尽管如此,我对如何使用 addObserver 方法感到困惑当 runningApplications
的 active
属性发生更改时收到通知。现在,我想知道在哪里进行注册,现在我正在使用 -applicationDidFinishLaunching
但不确定是否是正确的位置。另外,如果我使用 -observeValueForKeyPath 回调方法,我必须在继承自 NSObject
的类中实现它,并且与我注册通知的类是同一类?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该对
runningApplications
数组中的每个对象调用addObserver:...
方法(使用isActive
作为关键路径)。 p>在应用程序完成启动后开始观察听起来很正确。从时间上来说,就是这样。至于地点,应该有一个单独的类专门负责这些观察。通过在应用程序委托中实现观察代码,您将违反单一职责原则(从长远来看,这意味着令人头疼)。
observeValueForKeyPath:...
回调应该由调用addObserver:...
方法的对象实现。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.只需将此代码添加到您的 AppDelegate 或任何其他仍处于活动状态的类中即可:
Just add this code to your AppDelegate or to any other of your classes that remain alive: