How to cleanly encapsulate and execute in sequence

2019-04-17 11:40发布

问题:

My app includes a back-end server, with many transactions which must be carried out in the background. Many of these transactions require many synchronous bits of code to run.

For example, do a query, use the result to do another query, create a new back-end object, then return a reference to the new object to a view controller object in the foreground so that the UI can be updated.

A more specific scenario would be to carry out a sequence of AJAX calls in order, similar to this question, but in iOS.

This sequence of tasks is really one unified piece of work. I did not find existing facilities in iOS that allowed me to cleanly code this sequence as a "unit of work". Likewise I did not see a way to provide a consistent context for the "unit of work" that would be available across the sequence of async tasks.

回答1:

I recently had to do some JavaScript and had to learn to use the Promise concept that is common in JS. I realized that I could adapt this idea to iOS and objective-C. The results are here on Github. There is documentation, code and unit tests.

A Promise should be thought of as a promise to return a result object (id) or an error object (NSError) to a block at a future time. A Promise object is created to represent the asynchronous result. The asynchronous code delivers the result to the Promise and then the Promise schedules and runs a block to handle the result or error.

If you are familiar with Promises on JS, you will recognize the iOS version immediately. If not, check out the Readme and the Reference.



回答2:

I've used most of the usual suspects, and I have to say that for me, Grand Central Dispatch is the way to go.

Apple obviously care enough about it to re-write a lot of their library code to use completion blocks.

IIRC, Apple have also said that GCD is the preferred implementation for multitasking.

I also remember that some of the previous options have been re-implemented using GCD under the hood, so you're not already attached to something else, Go GCD!

BTW, I used to find writing the block signatures a real pain, but if you just hit return when the placeholder is selected, it does all that for you. What could be sweeter than that.