重新打開數據庫當然比保持打開時間要花費更多的時間。但是,這可能不是很明顯的時間。
我建議你創建一個Grand Central Dispatch queue並將其用於所有數據庫訪問。這裏是你如何創建它:
// The queue needs to be a global variable, or globally accessible in some way.
dispatch_queue_t dbQueue;
// Make your sqlite3 connection global too.
sqlite3 *dbConnection;
// In your application delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// usual initialization ...
...
int rc = sqlite3_open(dbFilename, &dbConnection);
if (rc != SQLITE_OK)
handleDbError(rc, dbConnection);
dbQueue = dispatch_queue_create("dbQueue", DISPATCH_QUEUE_SERIAL);
...
}
這裏是你如何使用它:
dispatch_queue_async(dbQueue, ^{
// This block runs off the main thread, and does not run simultaneously
// with any other blocks submitted to `dbQueue`.
NSString *result = executeDatabaseQuery();
dispatch_queue_async(dispatch_get_main_queue(), ^{
// This block runs on the main thread.
[(MyAppDelegate *)[UIApplication delegate] presentResult:result];
});
});
如果我有需要的不僅僅是我可以直接返回值返回值某些功能或者我需要實現一些功能爲了得到結果,你可以提到一些叫做presentResult的東西。感謝您的快速回復。 – Ekra
你需要實現像presentResult這樣的函數。 –
你好我喜歡你的答案,但我想問。當數據庫應該關閉? – Streetboy