iOS开发真机上数据库无法写入

时间:2019-01-23
本文章向大家介绍iOS开发真机上数据库无法写入,主要包括iOS开发真机上数据库无法写入使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

问题

在使用数据库的时候,模拟器上能对数据库进行增删改等操作,但是在真机上运行就无法进行这些操作了.

解决

在模拟器和真机上数据库存储的文件夹不同,而在真机上 "苹果" 是限制在 沙盒内的三个文件夹 以外的文件夹进行修改的,所以需要把数据库拷贝到沙盒中.

代码

// 获取 Document 文件夹

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

// 路径 

NSString *documentsDirectory = [paths firstObject];

// 获取数据库路径   dataBaseName : 数据库名称

NSString *documentLibraryFolderPath = [documentsDirectory stringByAppendingPathComponent:@"dataBaseName"];

// 判断数据库是否在目录下,如果没有就创建(拷贝)进来

if ([[NSFileManager defaultManager] fileExistsAtPath:documentLibraryFolderPath]) {

        NSLog(@"文件已经存在了");

}else {

        NSString *resourceSampleImagesFolderPath =[[NSBundle mainBundle]

                                                       pathForResource:@"dataBaseName"

                                                       ofType:@"db"];

         NSData *mainBundleFile = [NSData dataWithContentsOfFile:resourceSampleImagesFolderPath];

         [[NSFileManager defaultManager] createFileAtPath:documentLibraryFolderPath

                                                    contents:mainBundleFile

                                                  attributes:nil];

        }

// 获取数据库

_dataBase = [FMDatabase databaseWithPath:documentLibraryFolderPath];