Before keeping on reading in the docs, my brain got stuck at this point:
- (void)threadMainRoutine {
BOOL moreWorkToDo = YES;
BOOL exitNow = NO;
NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; // is this THE run loop?
// some stuff...
while (moreWorkToDo && !exitNow) { // or is THIS the run loop?
// some stuff
[runLoop runUntilDate:[NSDate date]];
// some stuff
}
// some stuff
}
I've added some comments in the code example. Maybe someone can explain this, why there's a while loop if there's a runLoop object that receives a -runUntilDate: message. I mean: Who is the loop here? I see two. First the while that's obviously a running loop, and then it calls a method that sounds like running a loop a well.
stateConfused = YES;
pleaseExplain = YES;
Technically, the
NSRunLooploops internally (it loops "until date"). This gives you a periodic opportunity to quit the thread -- if you useruninstead ofrunUntilDate:then theNSRunLoopwill loop internally forever (you won't need to wrap it in a while loop but you can never stop it either). This is the normal behavior for the main thread, not worker threads which typically have exit conditions that need periodic checking.The
runLoopwill never change the value ofmoreWorkToDoorexitNow(you are responsible for doing this when the thread's work is done or the user has quit your application) but these are how you decide if you want the thread to terminate.Depending on how you want your thread to behave, you can replace these flags with
[NSApp isRunning]and[tasksRemainingForThisThreadToProcess count] != 0or similar.(Race condition warning: If you end the thread when all remaining tasks are processed, be careful to never send another task to the thread when the
tasksRemainingForThisThreadToProcessis empty since this is an indication that the thread will quit).