dispatch_async and calling a completion handler on the original queue

后端 未结 4 1762
忘掉有多难
忘掉有多难 2020-12-08 10:26

I\'ve seen some related questions but none seem to answer this case. I want to write a method that will do some work in the background. I need this method to call a completi

4条回答
  •  暖寄归人
    2020-12-08 11:13

    If you look through the Apple docs, there appear to be two patterns.

    If it is assumed that the completion handler is to be run on the main thread, then no queue needs to be provided. An example would be UIView's animations methods:

    + (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion
    

    Otherwise, the API usually asks the caller to provide a queue:

    [foo doSomethingWithCompletion:completion targetQueue:yourQueue];
    

    My suggestion is to follow this pattern. If it is unclear which queue the completion handler should be called, the caller should supply it explicitly as a parameter.

提交回复
热议问题