36974

Return an array after a completion block has finished

Question:

I have the following function

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{ AppDelegate* appDelegate = [UIApplication sharedApplication].delegate; _currentStart = startDate; _currentEnd = lastDate; if(appDelegate.internetActive){ Webservice *web = [[Webservice alloc]init]; [web fetchAppointmentsOnCompletionFor:startDate andEnd:lastDate OnCompletion:^(BOOL finished) { if(finished){ [self generateRandomDataForStartDate:startDate endDate:lastDate]; // NOW return the self.dataArray } }]; } return self.dataArray; }

I can't figure out how I can return the self.dataArray when the completionblock has finished. Because my self.dataArray is filled inside the method generateRandomDataForStartDate:startDate . So at the moment the function always returns an empty array.

Thanks in advandce

Answer1:

You should pass the completion handler block inside the argument. Make the return type to void.

Caller object will write below code:

[calenderView calendarMonthView:monthView marksFromDate:startDate toDate:lastDate completionHandler:^(NSarray *dataArray){ //Process data array over here }]; - (void) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate completionHandler:(void (^)(NSArray*))completionBlock{ AppDelegate* appDelegate = [UIApplication sharedApplication].delegate; _currentStart = startDate; _currentEnd = lastDate; if(appDelegate.internetActive){ Webservice *web = [[Webservice alloc]init]; [web fetchAppointmentsOnCompletionFor:startDate andEnd:lastDate OnCompletion:^(BOOL finished) { if(finished){ [self generateRandomDataForStartDate:startDate endDate:lastDate]; completionBlock(self.dataArray); } }]; } completionBlock(self.dataArray); }

In the caller code handle completion block with response array received as argumnet.

Answer2:

You don't need to return an array from this method, As you mentioned that your dataArray is filling under the generateRandomDataForStartDate:startDate Method, So you can process the filled array from that method, So your code will be,

- (void) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{ AppDelegate* appDelegate = [UIApplication sharedApplication].delegate; _currentStart = startDate; _currentEnd = lastDate; if(appDelegate.internetActive){ Webservice *web = [[Webservice alloc]init]; [web fetchAppointmentsOnCompletionFor:startDate andEnd:lastDate OnCompletion:^(BOOL finished) { if(finished){ [self generateRandomDataForStartDate:startDate endDate:lastDate]; // NOW return the self.dataArray } }]; } }

And your method , which is populating the array, should return the modified array,

-(NSArray *)generateRandomDataForStartDate:(NSString *)startDate endDate:(NSString *)endDate { // Your code here to populate and filling array return self.dataArray; }

Recommend