Obj- C Configure Run Loop for NSDistributionNotifi

2019-08-11 06:39发布

问题:

I am making a simple IPC module for my helper task,

I decided to use NSDistributionNotificationCenter because of it's simplicity.

However I think that it need to be run in a runloop which I don't have, So I need to create a RunLoop.

I have read the documentation about RunLoops here https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html

However it is not clear for me, how should I do this RunLoop only for receiving and sending Notifications.

Can some1 insight me what my RunLoop should include ?

Should it include a timer ? How can I attach the message listener in to this RunLoop ?

I am sorry if my question is a bit noobish - I never messed manually with runloops before.

I understand that I have to create a thread and assign a runloop to it, But it is not clear how do I adding observers? should I add any additional things to it ?

回答1:

Actually it was much easier than I thought I am answering my own question in case that if someone will struggle with the very same thing in future he may find an answer here or at least a kickstart.

    BOOL done = NO;

    NSDistributedNotificationCenter * notificator = [NSDistributedNotificationCenter defaultCenter];
    [notificator addObserver:self selector:@selector(gotObject:) name:@"com.ipc.test" object:nil];

    // Add your sources or timers to the run loop and do any other setup.

    do
    {
        // Start the run loop but return after each source is handled.
        SInt32    result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, YES);

        // If a source explicitly stopped the run loop, or if there are no
        // sources or timers, go ahead and exit.
        if ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished))
            done = YES;

        // Check for any other exit conditions here and set the
        // done variable as needed.
    }
    while (!done);

Actually now I found much simpler solution

        NSDistributedNotificationCenter * notificator = [NSDistributedNotificationCenter defaultCenter];
       [notificator addObserver:self selector:@selector(gotObject:) name:@"com.ipc.test" object:nil];

        CFRunLoopRun();