将sqlite数据库复制到用户目录

六月ゝ 毕业季﹏ 提交于 2019-12-05 23:48:40

Sqlite如何在IOS开发中应用是本文要介绍的内容,主要是来学习在IOS开发sqlite数据库的使用方法。sqlite数据库初始化,复制到用户目录,并判断是否数据库已经存在,或者复制是否成功!

在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];  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!