Каждый NSThread
может предоставить NSRunLoop
, поэтому писать там нечего. Все, что вам действительно нужно, это периодически прокачивать NSRunLoop (при условии, что вы не прикрепили ни один из объектов, таких как NSTimer
, которые неявно делают это за вас).
Так, например,
// create a thread and point it to an agent that
// knows how to pump the run loop
myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(startRunLoop)
object:nil];
// start the thread
[serialDispatchThread start];
/* ... elsewhere ... */
- (void)startRunLoop
{
// consider setting a thread name here, as it'll help with debugging
// I'm lazily using a volatile bool for my quit flag; do whatever you
// think is appropriate
while(!quitThread)
{
// run the runloop for another 2 seconds,
// wrapping it in an autorelease pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSRunLoop currentRunLoop] runUntilDate:
[NSDate dateWithTimeIntervalSinceNow:2.0]];
[pool drain];
}
}
/* puts you in a position to be able, whenever you want to issue things like: */
[self
performSelector:@selector(myAsynchronousAction)
onThread:myThread
withObject:nil
waitUntilDone:NO];
Итак, вы сделали что-то похожее на очередь последовательной отправки GCD.