如何向Apple事件监听器添加回调方法,如:
CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(IOPowerSourceCallbackType callback,
void *context);
如何将方法或块添加到以下方法中,以便在电源更改时我可以记录下面的内容,(我可以看到它是C ++但NSLog仍然在Obj-C ++中工作)类似于:< / p>
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(callbackMethod(),
void *context);
}
void callbackMethod(){
// NSLog("No power connected"); or NSLog("Power connected");
}
我想我需要改变:
IOPowerSourceCallbackType callback
指针还是什么?
答案 0 :(得分:0)
documentation未列出IOPowerSourceCallbackType
类型,但它在<IOKit/ps/IOPowerSources.h>
标题中声明为:
typedef void (*IOPowerSourceCallbackType)(void *context);
这意味着您将回调定义为:
void callback(void *context)
{
// ...
}
您可以使用以下代码将其传递给IOPSNotificationCreateRunLoopSource
:
CFRunLoopSourceRef rls = IOPSNotificationCreateRunLoopSource(callback, whateverValueIsMeaningfulToYourCallback);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
CFRelease(rls);
您需要仔细考虑要在哪种模式下安排源的运行循环。如果您以后需要对运行循环源(rls
)执行更多操作,请不要立即释放它。将它保存在实例变量或类似的东西中,并在完成后释放它。特别是,您可能希望在某些时候使用CFRunLoopSourceInvalidate()
使其无效。