Created
May 13, 2016 02:15
-
-
Save mr5z/815d15fa373e049074ae85b049e01ec8 to your computer and use it in GitHub Desktop.
query database asynchornously
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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