So I have a function that prepares a code block and schedules it to run synchronously on a serial dispatch queue. I'm aware that this serial queue will be run on a new thread. The problem, however, is that the code block modifies a variable that it communicates back to the function which in turn is expected to return it as its return value. The code below will help clarify the situation:
-(DCILocation*) getLocationsByIdentifier: (NSString*) identifier andQualifier: (NSString*) qualifier {
__block DCILocation* retval = nil;
NSString* queryStr = [self baseQueryWithFilterSet:nil];
queryStr = [queryStr stringByAppendingString:@" (identifier = ? OR icao = ?) AND qualifier = ?"];
[self.queue inDatabase:^(FMDatabase *db) {
FMResultSet* results = [db executeQuery:queryStr,
[identifier uppercaseString],
[identifier uppercaseString],
[qualifier uppercaseString]];
if ((nil != results) && [results next]) {
dispatch_async(dispatch_get_main_queue(), ^{
retval = [DCIAirportEnumerator newAirportForStatement:results];
});
[results close];
}
}];
return retval;
}
"self.queue" is the serial dispatch queue that the block will run on. Notice that the block modifies "retval" and updates it by nesting a dispatch_async call to the main thread. The concern however, is that "return retval" (the last line of the function) could be possibly called before the block of code running on the serial dispatch queue is able to modify it. This will result in "nil" being returned.
Any ideas as to how it can be made sure that the function doesn't return until retval as been modified by the block executing on the serial queue?