简体   繁体   中英

Do RestKit completion blocks run on the main UI thread?

My code tells me it is via [NSThread currentThread] isMainThread] and the fact that I can show a UIAlertView as well. This seems unexpected because my understanding is that requests are dispatched asynchronously.

I'd throw in some relevant code, but it's nothing special. I POST an object via the RKObjectManager and the success and failure completion blocks execute on the main UI thread (even though I am definitely doing stuff in the background after the request completes).

I'm confused.

What's going on?

RKObjectManager behind the scenes creates and posts an RKObjectRequestOperation (which is essentially representation of your POST request) into NSOperationQueue to perform all the networking and mapping stuff asynchronously in the background thread.

When request is finished and response processed - default behavior is to run success or failure callbacks on the main thread. This is nice quick setup that helps you to build an app very fast and easy (and not worry about updating UI on the right thread).

You can easily change that behavior, RKObjectRequestOperation has 2 properties, successCallbackQueue and failureCallbackQueue , you can set them to be another background thread, and then when you need to change something on the UI side, just wrap that change into a block and post to main queue:

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    }];

The reason why you want requests are dispatched asynchronously because you don't want UI Thread (which is main thread) blocked by the request. because when it blocked , your App wont react user's action , that's a bad user experience.

Then after the request is done, you want to let the user know it, so the dispatched thread must return to main thread. in your situation, that's the completion block. then you can do things like show alert on the main thread.

I hope this is the answer you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM