-1

I've been away from iOS and programming for a long time and getting back in to it and I'm lost on how best to handle blocks inside methods that return data back to another class.

I created a method to download some data from the internet.

-(NSArray*) getDataFromWeb
{
    DataSync * dataS = [[DataSync alloc] init];

    [dataS downloadData:@"Full"
                              successBlock:^(NSArray *dataArray)
     {
         NSLog(@"Data : %@", dataArray);
         myDataArray = [dataArray copy];
     }
                                errorBlock:^(NSError *error)
     {
         NSLog(@"ERROR: %@",error);
     }];


return myDataArray;
}

Normally in the past I would have had a return statement returning the array. But because the block is off getting data on another thread the return will fire too early and the data wont have been retrieved and I just get a (null) back.

What is the recommended way to pass the data back to another class that is called this method after the block has finished it work and populated the array with data? Can I have two return states in each of the success or error section of the blocks?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Hi Matt, that is a swift question. Thanks -Code –  Feb 23 '16 at 00:18
  • Doesn't matter; the answer is still correct and directly applicable to your question. You need to call out to your update code from the completion blocks. – bbum Feb 23 '16 at 03:00

1 Answers1

0

There are two options.

No. 1, and I don't recommend this, is to wait for the block to finish and the return the value. Like I said, you should avoid this unless you REALLY know what you are doing, for this reason, I'm not going to go into details on it's implementation.

No. 2 is to not return the value, but to handle it with a completion block. Basically, you make your function return void, and add a block parameter with an object argument. A call to this method would look a lot like the call to downloadData.

Let's say your method now looks like this -(void)getDataFromWebWithCompletion:(CompletionBlock)block, at the end of the block for downloadData, you would do something like this:

if(block){
  block(dataArray)
}
EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50