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

前端 未结 2 1701
执笔经年
执笔经年 2020-12-16 20:48

Is it generally a good idea to call -[NSRunLoop runUntilDate:]? It seems to work without any issues, but it makes me nervous to tell the run loop to run from w

相关标签:
2条回答
  • 2020-12-16 20:59

    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);
    
    0 讨论(0)
  • 2020-12-16 21:12

    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.

    0 讨论(0)
提交回复
热议问题