Question

sleep works well but runUntilDate doesn't work on a background thread. But why?

-(IBAction) onDecsriptionThreadB:(id)sender
{
 dispatch_async(dispatch_get_global_queue(0, 0), ^{

    while (1)
    {
        NSLog(@"we are here");
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
        //sleep(2);
    }        
  });    
}
Was it helpful?

Solution

If no input sources or timers are attached to the run loop, this method exits immediately;

If you want to use runUntilDate you must add timer or input sources. My correct version is:

while (1)
{
    NSLog(@"we are here");
    [NSTimer scheduledTimerWithTimeInterval:100 target:self selector:@selector(doFireTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
    //sleep(2);
}  

OTHER TIPS

Take a look at the question Difference in usage of function sleep() and [[NSRunLoop currentRunLoop] runUntilDate]

NSRunLoop is better because it allows the runloop to respond to events while you wait. If you just sleep your thread your app will block even if events arrive (like the network responses you are waiting for).

Also the documentation of NSRunLoop says that:

If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate: until the specified expiration date.

If you are using GCD, the purpose is to generally get away from doing complicated thread coding right. What is the bigger purpose of you trying to do this. May be your big picture context will help explain the problem better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top