iOS关于数据库操作之二 将工程里的数据库文件在程序加载时移至沙盒

来源:互联网 发布:新闻类app源码 编辑:程序博客网 时间:2024/06/10 21:20
 iOS程序要访问本地数据库,就只能访问沙盒中的文件,之前我在用模拟器开发的时候,会把数据库的sql文件直接拖进模拟器的沙盒里,程序功能能够正常实现。但是如果用真机的话,这种做法是万万不可取的,因为在程序安装到机器之前,手机或者iPad上并不存在与该程序对应的沙盒,普通用户更是不可能找到这个沙盒。因此,正确的做法是:将数据库文件放在工程中,在程序第一次加载的时候,将数据库移至程序沙盒。 

具体操作如下: 

+(void)moveToDBFile
{       //1、获得数据库文件在工程中的路径——源路径。
NSString *sourcesPath = [[NSBundlemainBundle] pathForResource:@"database"ofType:@"sqlite"];

        //2、获得沙盒中Document文件夹的路径——目的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *desPath = [documentPath stringByAppendingPathComponent:@"database.sqlite"];

       //3、通过NSFileManager类,将工程中的数据库文件复制到沙盒中。
NSFileManager *fileManager = [NSFileManagerdefaultManager];
if (![fileManager fileExistsAtPath:desPath]) 
{
NSError *error ;
 
if ([fileManager copyItemAtPath:sourcesPath toPath:desPath error:&error]) {
NSLog(@"数据库移动成功");
}
else {
NSLog(@"数据库移动失败");
}
 
}

}
 
在程序中的加载的入口方法中调用该方法,即可在程序加载的时候将数据库文件添加的沙盒。然后从沙盒中读取数据库文件 .

//1、在全局中声明一个静态db对象
 
static FMDatabase *db = nil;
 

//2、获得沙盒数据库文件的路径
 
+(NSString *)databaseFilePath
{
NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [filePath objectAtIndex:0];
NSLog(@"%@",filePath);
NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"database.sqlite"];
return dbFilePath;
 
}
 
//3、从指定沙盒中获得数据库并将对象返回给调用者
+(FMDatabase *)getDatabase
{
        
if (!db) {
                //如果db对象不为空,从指定路径中得到数据库。这里已经要记得 retain, 否则在后面会引起程序崩溃。
db = [[FMDatabasedatabaseWithPath:[selfdatabaseFilePath]] retain];
}
returndb;

}


转载

0 0
原创粉丝点击