How to carefully encapsulate and perform a series of background tasks in iOS sequentially?

My application includes a server server with many transactions that must be performed in the background. Many of these transactions require many synchronous bits of code.

For example, run a query, use the result to execute another query, create a new internal object, then return the link to the new object to the view controller object in the foreground so that the user interface can be updated.

A more specific scenario would be to execute an AJAX call sequence in an order similar to this question , but on iOS.

This sequence of tasks is truly a single work. I did not find existing objects in iOS, which allowed me to clearly encode this sequence as "units of work . " Similarly, I have not seen a way to provide a consistent context for a β€œunit of work” that will be available in a sequence of asynchronous tasks.

0
source share
2 answers

I recently had to make JavaScript and had to learn to use the concept of Promise, which is common in JS. I realized that I can 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 seen as a promise to return a result object (id) or an error object (NSError) in a block in the future. A Promise object is created to represent an asynchronous result. Asynchronous code passes the result to Promise, and then to the Promise schedule and runs the block to handle the result or error.

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

+2
source

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

Apple clearly takes care of this to rewrite a lot of its library code to use completion blocks.

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

I also remember that some of the previous options were reimplemented using GCD under the hood, so you are not connected to anything else, Go GCD!

By the way, I used a lot of pain to write block signatures, but if you just press return when the selector, it will do all this for you. What could be sweeter than that.

+2
source

Source: https://habr.com/ru/post/1480004/


All Articles