简体   繁体   中英

Upload the data using Grand Central dispatch queue in iphone?

I have a number of data so I want upload the data in the GCD queue order like FIFO method. How to do that ?

Whatever is your "upload" block, you must create a GCD serial queue and then dispatch_async all your upload blocks on it.

To create the queue:

dispatch_queue_t myFifoQueue = dispatch_queue_create("com.example.myfifoqueue",DISPATCH_QUEUE_SERIAL);

Once you have create your queue you can now dispatch your upload blocks. To dispatch one of these blocks in the queue:

dispatch_async(myFifoQueue,myUploadBlock);

"dispatch_async" guarantees you that your blocks will be added in the serial queue but your current thread (usually the main thread) will not wait for the block to complete. Using a serial queue guarantees you that all blocks will be executed in FIFO order.

Eg if you have an NSArray *myArray and you want to process in the queue the array objects using a method called -(void)processObject:(id)object then you can write your code in this way:

for(id object in myArray) {
  dispatch_async(myFifoQueue,^{
      [self processObject:object];
  }
  );
}

Basically what you do here is to enumerate all objects in the array and then submit to the serial queue a simple block that calls the "processObject:" method. Whatever is the time taken by processObject to finish its task, dispatch_async will return immediately and the serial queue will process its blocks serially in a background thread. Note that you don't have here a way to know when all blocks are done, so it is a good idea to submit at the end of the queue some block that notifies the main thread of the end of the queue (so that you can update your UI):

dispatch_async(myFifoQueue,^{
dispatch_async(dispatch_get_main_queue(),
     ^{
        [self endOfUpload];
      });
});

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