B
B
Bookin2014-07-27 14:19:31
Objective-C
Bookin, 2014-07-27 14:19:31

Objective c, how to wait until block finishes?

There is a function that should return an array either from a file or download from the server and put it in this file. I ask this function to return an array, it returns an empty one, and after that it executes a request to the server, how to return data after downloading from the server?
Roughly what I have:

-(NSArray*)getData{
  __block NSArray *returnData = nil;
  if([self internetConnect]){
     [self reloadData:^(NSArray* loadData){
       returnData = loadData;
     }];
  }else{
     //тут проблем нет
  }
  return returnData;
}

The reload data method also has a block that loads data, in general, I think like this block with a block that all in a compartment load data and put it in an array, return from this getData method after everything has loaded.
Thanks in advance for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Averin, 2014-07-29
@Bookin

You want the current thread to wait for the asynchronous request to complete.

-(NSArray*)getData{
    __block NSArray *returnData = nil;
    if([self internetConnect]){
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){
            [self reloadData:^(NSArray* loadData){
                returnData = loadData;
            }];
        });
    }else{
        
    }
    return returnData;
}

You can also create your own competitive queue
+(dispatch_queue_t)sharedConcurrentQueue {
    static dispatch_queue_t queue = nil;
    static dispatch_once_t onceToken = 0;
    
    dispatch_once(&onceToken, ^{
        queue = dispatch_queue_create("MyQueueName", DISPATCH_QUEUE_CONCURRENT);
    });

    return queue;
}

And put any tasks in it in this way
-(void)testFunc {
    dispatch_async([MyClass sharedConcurrentQueue], ^(void){
        // Все, что хотим запустить и идти дальше, не дожидаясь
    });
    
    dispatch_sync([MyClass sharedConcurrentQueue], ^(void){
        // Все, что хотим запустить и подождать завершения
    });
}

You can read about it here .
Or google "Grand Central Dispatch".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question