background image

sqlite 数据库复制到用户目录

    qlite 如何在 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 }