开发者

How do you create a writable copy of a sqlite database that is included in your iPhone Xcode project?

开发者 https://www.devze.com 2022-12-23 12:33 出处:网络
copy it over to your documents directory when the app starts. Assuming that your sqlite db is in your project, you can use the below code to copy your database to your documents directory. We are als

copy it over to your documents directory when the app starts. Assuming that your sqlite db is in your project, you can use the below code to copy your database to your documents directory. We are also assuming that your database is called mydb.sqlite.

    //copy the database to documents
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
if(![fileManager fileExistsAtPath:path])
{
    NSData *data = [NS开发者_运维问答Data dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/mydb.sqlite"]];
    [data writeToFile:path atomically:YES];
}

Anyone know of a better way to do this. This seems to work ...


That looks valid to me. You can also just copy the file with this NSFileManager method instead:

- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;

I think using this method instead might be a bit more readable, but YMMV.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号