There's a better approach. Do not make any changes to your code that calls DBManager
. All changes should be made inside your DBManager
class. And there is no reason to use dispatch_async
. Use dispatch_sync
.
This code stays the same:
Class A
[[DBManager getInstance] insertRecord:@"12345"];
Class B
-(void)processData{
Record r = [[DBManager getInstance] getRecord];
// working with record r. after that doing some layout update
[self.lbTitle setText:r.name];
}
In your insertRecord:
method you change it to something like:
- (void)insertRecord:(NSString *)record {
dispatch__barrier_sync(CUSTOM_DB_QUEUE, ^{
// original code to insert record
};
}
And your getRecord
method becomes:
- (Record *)getRecord {
__block Record *result = nil;
dispatch_sync(CUSTOM_DB_QUEUE, ^{
// original code that sets result
};
return result;
}
By using dispatch_sync
and dispatch_barrier_sync
, this code allows for any number of concurrent calls to getRecord
but only one call to insertRecord
. It also ensures calls to getRecord
are blocked while insertRecord:
is being run.