objective-c - 如何在macOS的非主线程上发生事件循环?

标签 objective-c multithreading macos events nsworkspace

this other question相关:我需要在macOS上收集有关什么是当前 Activity 应用程序的信息。
链接的质量检查答案提供了一种机制,该机制可在 Activity 应用程序更改时获得警报(事件),但在单独的线程上运行时会崩溃:

FocusDetector::AppFocus focus;
focus.run();

//std::thread threadListener(&FocusDetector::AppFocus::run, &focus); //Does not works
//if (threadListener.joinable())
//{
//  threadListener.join();
//}
    *** Assertion failure in +[NSUndoManager _endTopLevelGroupings], /xxxxxxx/NSUndoManager.m:363
2020-11-24 08:54:41.758 focus_detection[81935:18248374] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+[NSUndoManager(NSInternal) _endTopLevelGroupings] is only safe to invoke on the main thread.'
*** First throw call stack:
(
    0   CoreFoundation            0x00007fff3006cb57 __exceptionPreprocess + 250
    1   libobjc.A.dylib           0x00007fff68eb35bf objc_exception_throw + 48
    2   CoreFoundation            0x00007fff30095d08 +[NSException raise:format:arguments:] + 88
    3   Foundation                0x00007fff32787e9d -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 191
    4   Foundation                0x00007fff326c45ee +[NSUndoManager(NSPrivate) _endTopLevelGroupings] + 440
    5   AppKit                    0x00007fff2d25165c -[NSApplication run] + 864
    6   focus_detection           0x0000000104b1a010 _ZN13FocusDetector8AppFocus3runEv + 128
    7   focus_detection           0x0000000104b19547 _ZNSt3__1L8__invokeIMN13FocusDetector8AppFocusEFvvEPS2_JEvEEDTcldsdeclsr3std3__1E7forwardIT0_Efp0_Efp_spclsr3std3__1E7forwardIT1_Efp1_EEEOT_OS6_DpOS7_ + 119
    8   focus_detection           0x0000000104b1944e _ZNSt3__1L16__thread_executeINS_10unique_ptrINS_15__thread_structENS_14default_deleteIS2_EEEEMN13FocusDetector8AppFocusEFvvEJPS7_EJLm2EEEEvRNS_5tupleIJT_T0_DpT1_EEENS_15__tuple_indicesIJXspT2_EEEE + 62
    9   focus_detection           0x0000000104b18c66 _ZNSt3__114__thread_proxyINS_5tupleIJNS_10unique_ptrINS_15__thread_structENS_14default_deleteIS3_EEEEMN13FocusDetector8AppFocusEFvvEPS8_EEEEEPvSD_ + 118
    10  libsystem_pthread.dylib   0x00007fff6a260109 _pthread_start + 148
    11  libsystem_pthread.dylib   0x00007fff6a25bb8b thread_start + 15
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6
显然,这与NSApplication有关,文档状态如下:

Every app uses a single instance of NSApplication to control the main event loop


因此,我正在寻找监听事件的另一种方法,该方法不限于主事件循环(或主线程)。
直观地,应该有可能在一个单独的线程中获得有关当前应用程序的信息。
我不知道如何解决这个问题,很抱歉没有提供太多研究。我曾在互联网上搜索过“NSNotification not in main thread”和其他类似句子,但没有成功。
问题:
如何在主线程外监听activeAppDidChange NSNotification?

最佳答案

将观察者放置在下面的以下通知中,并让它们调用您的方法。 NotificationCenter具有充分的理由是单例,当然您也可以创建自己的。我猜[NSWorkspace sharedWorkspace]是一个单例,而[[NSWorkspace sharedWorkspace] notificationCenter]命名为-要观察的通知中心。在您的情况下,期望的发送对象是nil,因为您不知道要观察哪个对象更具体。

#import <AppKit/AppKit.h>
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    [[[NSWorkspace sharedWorkspace] notificationCenter]
        addObserver:self
        selector:@selector(activeAppDidChange:)
        name:NSWorkspaceDidActivateApplicationNotification
        object:nil
    ];
    [[[NSWorkspace sharedWorkspace] notificationCenter]
        addObserver:self
        selector:@selector(activeAppDidTerminate:)
        name:NSWorkspaceDidTerminateApplicationNotification
        object:nil
    ];
    // id<NSObject> myObserver;
    _myObserver = [[[NSWorkspace sharedWorkspace] notificationCenter] 
        addObserverForName:NSWorkspaceDidHideApplicationNotification
        object:nil 
        queue:[NSOperationQueue mainQueue] 
        usingBlock:^(NSNotification * _Nonnull note) {
            // do stuff in block
            NSRunningApplication *app = note.userInfo[NSWorkspaceApplicationKey];
            NSLog(@"%u %@ %ld", 
               app.processIdentifier, 
               app.bundleIdentifier, 
               (long)app.activationPolicy
            );
        }
    ];
}
-(void)activeAppDidChange:(NSNotification *)note {
    NSLog(@"%@",note.userInfo.debugDescription);
}
-(void)activeAppDidTerminate:(NSNotification *)note {
    NSLog(@"%@",note.userInfo.debugDescription);
}

关于objective-c - 如何在macOS的非主线程上发生事件循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64967384/

相关文章:

C# BackgroundWorker 和 Com 端口问题

java - 在Runnable的整个生命周期中,Thread.currentThread()方法是否总是返回相同的对象?

c++ - 多个条件变量: threads out of sync problem

javascript - Safari - 按箭头键导航图库时发出错误声音

macos - 如何通过SSH获取在OSX终端中运行的命令的退出状态代码?

C++ 和 Objective-C

iphone - 您将如何最小化或压缩 Core Data sqlite 文件大小?

iphone 应用程序 NSNumber 内存泄漏

xcode - OS X Lion 上的 install_name_tool

ios - 被 NSMutableArray sortUsingDescriptors : exception 搞糊涂了