NSRunLoop- Clarification needed

冷暖自知 提交于 2019-12-03 16:32:22
  1. The change you see when you use run or runUntilDate: instead of runMode:beforeDate: is expected. The documentation for runMode:beforeDate: says this:

    it returns after either the first input source is processed or limitDate is reached.

    There is an input source responsible for handling the performSelector:... requests. So when you send performSelector:..., the run loop processes an input source and then returns.

    On the other hand, the documentation for run says this:

    it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:. In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers.

    So after the run loop processes the input source for your performSelector:... request, it waits for another input source to be ready. It doesn't return. Since it doesn't return, your while loop never gets a chance to test exitThread.

  2. Your attempt to use CFRunLoopStop is a good idea, but unfortunately, the documentation for run says this:

    If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop.

    So you can't rely on CFRunLoopStop to make run return.

    Instead, you can drop to a lower level and use CFRunLoopRun to run the run loop, because CFRunLoopStop is documented to make that function return:

    This function forces rl to stop running and return control to the function that called CFRunLoopRun or CFRunLoopRunInMode for the current run loop activation.

    So try this to run your run loop:

    while(!exitThread) {
        NSLog(@"Thread did some work");
        CFRunLoopRun([NSRunLoop currentRunLoop].getCFRunLoop);
    }
    

Documents of runMode:beforeDate: say:

Runs the loop once, blocking for input in the specified mode until a given date.

That mean it processes '@selector' input source only one time and then returns, not like run will continue to process next input source without returning.

However runUntilDate: will return after limit date if you code it as:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!