sqlite数据文件真机调试

项目用到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里,复制粘贴到工程路径,没有导入工程,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值