Sync request, asynchronous request, get request, POST request for iOS

Source: Internet
Author: User
Tags gcd

People who have had programming experience will almost always have access to multi-threaded pieces.

In Java and Android development, a large number of background operations, asynchronous Message Queuing, the basic use of multithreading to achieve.

Likewise, in iOS mobile development and Android are basically very similar to a model.

But most of the time, in application development, we find ourselves not coding to deal with some concurrent events, to open up new sub-threads and so on.

(Although the general call to the SDK to initiate a network request, the system will default to you a new thread to deal with).

The entire program looks basically executed in the main thread.

It is also a phenomenon, because basically we are manipulating the layout of the control, adding to the control data, and updating the UI object on the main thread.

Even if we see that we've opened a new sub-thread to get processing data, and finally need to refresh by notifying the UI thread.

Of course, iOS itself, like most languages, has nsthread threading classes (we all know we use this class in Java).

These systems compare the underlying API classes and can be used by me to write my own concurrent threads and operations queues.

Learn Android We all know handler,looper this concept, Looper is a main thread of the message loop queue, Handler general understanding is used for child threading and UI main thread some data interaction.

Look at the GCD features of iOS and find them quite a bit similar.


1. Here's how to use GCD programming asynchronous

[CPP]View Plaincopy
    1. Dispatch_async (dispatch_get_global_queue (0, 0), ^{
    2. //A block of code that handles time-consuming operations ...
    3. //Notify main thread Refresh
    4. Dispatch_async (Dispatch_get_main_queue (), ^{
    5. //callback or notify the main thread to refresh,
    6. });
    7. });


Dispatch_async Open an asynchronous operation, the first parameter is to specify a GCD queue, and the second parameter is to assign a program block that handles things to that queue.

Dispatch_get_global_queue (0, 0), refers to the use of the global queue.

In general, the system itself will have 3 queues.

Global_queue,current_queue, and Main_queue.

To get a global queue is to accept two parameters, the first one is the thing handler block queue priority I assign. Sub-level and default, 0 is the default 2 is high, 2 is low

[CPP]View Plaincopy
    1. #define Dispatch_queue_priority_high 2
    2. #define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
    3. #define Dispatch_queue_priority_low (-2)

After you have finished processing things, you need to return the results to or refresh the main thread of the UI, same as above, grab the main thread, and block the operation.


God, the hand is not careful to point to the home, will be back to find not saved ~ ~ ~ Write the concurrent piece of content is gone!!!

Second: The concurrency concept of GCD

In fact, for programming, we have been referring to several concepts, synchronous, asynchronous, concurrency, locks and so on.

Sometimes I find it very unclear.


Let's take a look at these 3 concepts in the picture above, which I understand.

1 synchronization:

[CPP]View Plaincopy
    1. for (int i = 0; i < i++) {
    2. UIImage *img = [self Getimgewith:[urlarr objectforindex:i];
    3. [Myimgv[i] setimage:img];
    4. }


Assuming I want to load 10 images, I now have the resource addresses for these images, which are saved in an array.

Let's take the first picture for example:

The concept of synchronous execution is that when I get the first picture,

After the first sentence of the for loop has been executed, I can execute the second sentence and refresh the UI interface.

If the first sentence takes 10 seconds to return, then my program responds as if it were stuck here, and I can't do anything else. Must wait for it to return!!

Therefore, a good understanding of the synchronization of the idea is that one step to go to the black.

2. Asynchronous

[CPP]View Plaincopy
  1. for (int i = 0; i < i++) {
  2. Dispatch_async (dispatch_get_global_queue (0, 0), ^{
  3. //A block of code that handles time-consuming operations ...
  4. UIImage *img = [self Getimgewith:[urlarr objectforindex:i];
  5. //Notify main thread Refresh
  6. Dispatch_async (Dispatch_get_main_queue (), ^{
  7. //callback or notify the main thread to refresh,
  8. [Myimgv[i] setimage:img];
  9. });
  10. });


Look at this code, we will say that the asynchronous operation of the hypothesis is still 10 seconds ah, the overall view, the execution of a picture of the time to load or about 10 seconds ah,

There seems to be no use for asynchrony. However, do not overlook one point, also the black core of the point, at this time we picture capture operations in a thread queue,

At the moment, although we look at the loading of the picture will take 10 seconds to come out, but, during this 10 seconds, our UI main thread can be manipulated, such as the interface has a button, you can press the

Instead of the synchronization above, in 10, I can only wait and do nothing.

The core concept of asynchrony is a new thread, a message callback notification.

3. Parallel

Let's just do the above code for example. As I emphasized earlier, we only look at the loading of a picture, and now, back at the first sight we see the code thinking up,

A For loop. In fact, after the code above, I created 10 asynchronous threads.

Well, to this, we should understand these three concepts.

synchronization, in fact, I have some limitations in the previous example, that is, the example itself shows that there is no need for synchronous execution, and then give everyone a big feeling is

Synchronization is a taboo point in programming, in fact, many times. We really need to synchronize to make some restrictions (such as the synchronization lock proposed in the thread)? Listen, do you feel useful?

Although it may not be the same as we think the use of synchronization, but at least to illustrate that the concept is also useful)

I still take the picture as an example, a simple explanation of how to use the benefits of synchronization.

Of course, I just simulate a synchronous situation.

Suppose we now load the picture is like this, the picture itself is a default picture before loading, it says, click I load, click on the network loading method will be called, and then the picture display loading,

Then we double-click the picture (of course, after the load is loaded) to read the image of the network image amplification, well, here should be able to think of the situation to express.

The whole process should be click on picture---load-double click to view. If it becomes a click-to-load (to return the author and information of the picture)-double-click the picture (larger image is displayed by the large image link returned by the previous request)-"

Full load returned (the large map link is returned). At this point we can't see the larger image of the picture. Because we operate before we return, that is to say,

Most of the time, the next action of our operation must need to use the data of the previous operation, we will give him the thought of synchronous programming, such as the addition of a button lock.

This is what we will be wondering, the next execution needs to use the previous execution, the first example of the For loop in the second sentence is not to use it, so to speak

They have to be synchronized, if you think so, it's a coincidence, we think of a go ~

However, note that the async we arrived at earlier is to resolve the action I clicked on the other buttons, rather than the update UI action. Downloading and updating UI operations must be synchronized in our view.

That's right, but the kind of thing that caused the system itself to listen to some of the monitoring events heard click Processing after that request, the loading picture here is actually considered an event execution,

Because this abstract unit of events is actually a kind of human-defined width.

That is, once the data gets and the image fills, actually is an image obtains the loading event, the event can say contains two units, loads and fills.

And the whole thing is nothing to do with the other buttons, so it doesn't have to be synchronized.

It makes sense, but if we're going to click on this image, we'll just go back to the hypothesis that we can double-click.

Here maybe I have overlooked a little bit why we can click on the load, and the assumption is that getting the picture has been done asynchronously, but we need to synchronize the next operation

So we did a man-made synchronization lock.

Well, that's too much to say, at least we understand two.

Async may be the main thread jam for a time-consuming operation,

Synchronization is to solve some unnecessary errors and troubles. Perhaps here, we think of the so-called thread safety in mind.

In fact, synchronization and synchronization lock, but it should be taken into account such unnecessary and unsafe factors.


Finally, the asynchronous and concurrent relationships are explained briefly.

Actually read the above said, async just provides a concept of multithreading,

Concurrency is a large-scale implementation that is more like async.

It is like saying that the asynchronous proposed can use the younger brother to collect the protection fee, has finished to tell and gives to oneself, but I in during the other to do the thing.

Concurrency suddenly thought, asynchronous this very reasonable Ah, then I have 4 places to collect, a younger brother to collect, although I can still do other things,

But the younger brother runs four places, I get the money the time needed to collect the same as myself, but I do not have so much effort, but also can do other things.

Therefore, concurrency feel should send four little brother to go, because each site protection fee is irrelevant. (Just watched a New York gang).


Therefore, asynchronous solves the thread jam, while concurrency is on the basis of asynchronous, which improves the processing time efficiency of conforming to the characteristic event.


Of course, if the 10 images themselves are not related to each other, however, the last event needs to be processed to calculate the total capacity value of these 10 images.

Then you can use Dispatch_group_async.

Just read the documentation.


On the whole, I looked at IOSGCD, one that made me familiar with the Block programming features, and how to use the GCD features provided by iOS.

To complete multithreaded programming.


Sync request, asynchronous request, get request, POST request for iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.