Skip to content

Instantly share code, notes, and snippets.

@mr5z
Created May 13, 2016 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/815d15fa373e049074ae85b049e01ec8 to your computer and use it in GitHub Desktop.
Save mr5z/815d15fa373e049074ae85b049e01ec8 to your computer and use it in GitHub Desktop.
query database asynchornously
- (void)query:(NSString *)query completion:(CompletionCallback)completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
while(isBusy) {
// wait for it
// or should I say, sleep?
}
isBusy = YES;
sqlite3_stmt *statement;
int prepareCode = sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL);
if (prepareCode != SQLITE_OK) {
NSString *error = [NSString stringWithFormat:@"%s", sqlite3_errmsg(database)];
completion(nil, error);
return;
}
int columnCount = sqlite3_column_count(statement);
NSMutableArray *result = [NSMutableArray new];
while (sqlite3_step(statement) == SQLITE_ROW) {
NSDictionary *row = [self bundle: statement columnCount: columnCount];
[result addObject:row];
}
sqlite3_finalize(statement);
int errorCode = sqlite3_errcode(database);
NSString *errMsg = (errorCode == SQLITE_OK) ? nil : [NSString stringWithFormat:@"%s", sqlite3_errmsg(database)];
completion(result, errMsg);
isBusy = NO;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment