Is calling -[NSRunLoop runUntilDate:] a good idea?

强颜欢笑 提交于 2019-11-29 04:04:55

You have to make sure not to do this from any method that could be called by the run loop you are invoking, unless the overlapping call tree is completely re-entrant.

The Cocoa Touch UI code is not documented as re-entrant (in fact, there are warnings/hints from Apple DTS that it is not), so if your fetch data handler can in any way be called by a UI method (or other non-reentrant code that could be called in the UI run loop), calling the UI run loop from inside it is not recommended.

Isn’t it better to display some kind of a spinner and tear it down in response to the async completion events from the networking code? Like:

[self displayLoadingSpinner];
[request setCompletionBlock:^{
    [self handleSuccess];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self hideLoadingSpinner];
    }];
}];
[request setFailedBlock:^{
    [self handleFailure];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self hideLoadingSpinner];
    }];
}];
[queue addOperation:request];

I would consider this better than monkeying with the run loop. But it could be that you already know this and just want to know what exact drawbacks are there in the runloop solution?


If you want to block until the value is ready, you can use a semaphore:

dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[request setCompletionBlock:^{
    dispatch_semaphore_signal(sem);
}];
[queue addOperation:request];

dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_release(sem);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!