將sqlite數據庫複製到用戶目錄

Sqlite如何在IOS開發中應用是本文要介紹的內容,主要是來學習在IOS開發sqlite數據庫的使用方法。sqlite數據庫初始化,複製到用戶目錄,並判斷是否數據庫已經存在,或者複製是否成功! sql

在AppDelegate.m中輸入如下代碼,以便複製預置數據庫到指定doucment目錄 數據庫

 
  1. - (BOOL) initializeDb {  
  2. NSLog (@"initializeDB");  
  3. // look to see if DB is in known location (~/Documents/$DATABASE_FILE_NAME)  
  4. //START:code.DatabaseShoppingList.findDocumentsDirectory  
  5. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  6. NSString *documentFolderPath = [searchPaths objectAtIndex: 0];  
  7. //查看文件目錄  
  8. NSLog(@"%@",documentFolderPath);  
  9. dbFilePath = [documentFolderPath stringByAppendingPathComponent:@"shopping.db"];  
  10. //END:code.DatabaseShoppingList.findDocumentsDirectory  
  11. [dbFilePath retain];  
  12. //START:code.DatabaseShoppingList.copyDatabaseFileToDocuments  
  13. if (! [[NSFileManager defaultManager] fileExistsAtPath: dbFilePath]) {  
  14. // didn't find db, need to copy  
  15. NSString *backupDbPath = [[NSBundle mainBundle] pathForResource:@"shopping" ofType:@"db"];  
  16. if (backupDbPath == nil) {  
  17. // couldn't find backup db to copy, bail  
  18. return NO;  
  19. } else {  
  20. BOOL copiedBackupDb = [[NSFileManager defaultManager] copyItemAtPath:backupDbPath toPath:dbFilePath error:nil];  
  21. if (! copiedBackupDb) {  
  22. // copying backup db failed, bail  
  23. return NO;  
  24. }  
  25. }  
  26. }  
  27. return YES;  
  28. //END:code.DatabaseShoppingList.copyDatabaseFileToDocuments  
  29. NSLog (@"bottom of initializeDb");  
  30. }  
  31. - (void)applicationDidFinishLaunching:(UIApplication *)application {  
  32. // copy the database from the bundle if necessary  
  33. if (! [self initializeDb]) {  
  34. // TODO: alert the user!  
  35. NSLog (@"couldn't init db");  
  36. return;  
  37. }  
  38.     // Add the tab bar controller's current view as a subview of the window  
  39.     [window addSubview:tabBarController.view];  
相關文章
相關標籤/搜索