项目用到sqlite3数据库,需要在真机运行时,把SQLite数据文件导入iphone,这主要涉及打开操作预置数据文件。
方法:把预置文件丢进mainBundle,然后设置在程序启动后,从mainBundle复制过去。步骤如下:
1.把SQLite数据文件导入工程
2.在应用代理类的application didFinishLaunchingWithOptions添加如下代码,用于区分是否为真机运行
#if TARGET_IPHONE_SIMULATOR
#else
[self createEditableCopyOfDatabaseIfNeeded];
#endif
3.还是在应用代理类写具体方法实现:
-(void)createEditableCopyOfDatabaseIfNeeded
{
// 先判断 sandbox 下面的 documents 子文件夹里面有没有数据库文件 test.sqlite
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
/*
NSString *documentsDirectory=NSHomeDirectory();
NSLog(@"%@",documentsDirectory);
documentsDirectory=[documentsDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
*/
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
BOOL ifFind = [fileManager fileExistsAtPath:writableDBPath];
if (ifFind)
{
// NSLog(@"数据库已存在");
return;
}
else{
NSLog(@"数据库不存在,需要复制");
}
// 如果不存在数据库文件,则复制数据库文件
NSLog(@"[NSBundle mainBundle]是%@",[NSBundle mainBundle]);
/*
NSBundle </private/var/mobile/Containers/Bundle/Application/0F29B1F5-54C0-459F-B3C2-C17F0CF62E27/ESP3.app> (loaded)
NSBundle </private/var/mobile/Containers/Bundle/Application/75291FDA-EA21-49B0-807F-FFBE6A0DA6DE/ESP3.app> (loaded)
NSBundle </private/var/mobile/Containers/Bundle/Application/37AC6FBC-1682-4AA6-8F83-973BE952DE54/ESP3.app> (loaded)
*/
NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"mydb" ofType:@"sqlite"];
// NSLog(@"%@",defaultDBPath);
BOOL ifSuccess = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!ifSuccess) {
NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}else {
NSLog(@"createEditableCopyOfDatabaseIfNeeded 初始化成功");
}
return;
}
注意:1.数据文件名字及存放路径要对,以后对文件增删查改操作之前,对文件打开都要去这个路径。
2.文件复制需要时间,如果嫌放在启动时复制费时间,可以把这个方法放其它地方。
3.我之前掉坑里,网上查了说要把文件放进resource文件夹,我在finder里把数据文件复制到工程路径,没有导入工程,总崩溃报错
source path is nil,每次运行打印mainBundle总在固定路径下创建新文件夹,还有对资源文件理解不清,甚至不知道在哪里,资源就是运行时用到的各种图片,就是assert。
我是把mydb.sqlite拖进Assets.xcassets,在这个地方我掉坑里了:我看网上说导入到resources文件夹下,我直接在finder里,复制粘贴到工程路径,没有导入工程,