将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];  
相关文章
相关标签/搜索