babygau
babygau

Reputation: 1581

Using Blocks and GCD to manage tasks

I'm learning iOS and when it comes to GCD, it's confusing. Let's get it out of the way, I'm writing a small program that fetch data from the internet. Here is my viewcontroller

NSMutableArray dataArray = [NSMutableArray array];

[querysomethingwithblock:(^ {
   //do some stuff here
   [otherquerywithblock:( ^ {
       //do some stuff here
       // Here I got the data from internet
       // Do loop action
       [dataArray addObject:data];
   })];


})];
// here I want to perform some actions only after get data from internet
[self performAction:dataArray];

How can I achieve this purpose. In practical, [self performAction:dataArray] always get fired before I get the data. I tried to play with GCD but no luck.

Here is some patterns I've tried so far

dispatch_async(queue, ^{
    // Do query stuff here
    dispatch_async(dispatch_get_mainqueue(), ^{
       //perform action here
    });
{;

Or using dispatch_group_async, dispatch_group_wait, dispatch_group_notify

The only way I can handle right now is to use dispatch_after but the point is the downloading time is variable, it's not good practice to have a specific time here

Thank you so much for any advice.

Upvotes: 0

Views: 108

Answers (1)

micantox
micantox

Reputation: 5616

The part of code called Do query stuff here i assume is async already, why put it inside a dispatch_queue then?

If instead you manage to do a synchronous query, your code (the second snippet) would work, as the dispatch to the main queue would be executed only after the query finished.

If you don't have an option to execute the query in a synchronous manner, then you need some mechanism to register either a block or a callback to be executed when the download is finished.

At the end of the day, it all depends on what kind of query you have in there and what methods it offers for you to register an action to be performed when the download is finished.

Upvotes: 1

Related Questions