Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Run Loop which is kicked only by performSelector... method calls?

I'm messing around with threads a little bit. Now consider this: I have a main thread. I start a new thread. In it's entry-point method, I want to make a run loop. Now the documentation tells meh that I have to have a input source. Otherwise my run loop exits immediately. bad. okay. but I have no other input source than my performSelector... method calls. After the thread is started, there comes a performSelector method that will kick in another method on that thread after some delay. inside that method another performSelector call happens, and so on. each with a delay between 0.1 and 1 sec. So a repeatedly firing timer is senseless right ;-)

How could I set up that run loop so it keeps alive to receive kicks from performSelector? I want the thread to sleep when there's nothing to do. but when a performSelector kick is comming in his butt, I want that the thread wakes up and works.

Any suggestions, anyone?

like image 828
user195531 Avatar asked Nov 06 '22 19:11

user195531


1 Answers

The code you want is explained in Figure 3-14 in Run Loops in the Threading Programming Guide. But it's buried so well in other discussion that if you don't understand everything else on this page, you won't quite know what you're looking at. Read that section, and then this code will hopefully make sense:

- (void)startRunLoop:(id)sender
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Any thread setup

    do
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate distantFuture]];
    } while (self.isStarted);

    // Any thread cleanup

    [pool release];
}
like image 89
Rob Napier Avatar answered Nov 12 '22 13:11

Rob Napier