我想将数据库文件从bundle复制到用户文档。
我的代码如下:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *userPath = [documentsDir stringByAppendingPathComponent:@"db.sql"];
NSString *srcPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sql"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(@"Bundle database exists: %i",[fileManager fileExistsAtPath:srcPath]);
NSLog(@"User Document folder database exists: %i",[fileManager fileExistsAtPath:userPath]);
BOOL find = [fileManager fileExistsAtPath:userPath];
BOOL copySuccess = FALSE;
NSError *error;
if (!find) {
NSLog(@"don't have writable copy, need to create one");
copySuccess = [fileManager copyItemAtPath:srcPath toPath:userPath error:&error];
}
if (!copySuccess) {
NSLog(@"Failed with message: '%@'.",[error localizedDescription]);
}
结果总是说:
捆绑数据库存在:1个用户文档文件夹数据库存在:0
没有可写副本,需要创建一个失败的消息:' 操作无法完成。 (可可错误4。)'。
请建议,谢谢。
答案 0 :(得分:2)
您确定用户文档目录的代码不正确。
使用你的代码,我整理了一个快速而肮脏的样本。对于您的应用程序,您可能希望创建一些包含静态函数“applicationDocumentsDirectory”的utils类,以便项目中的其他类可以根据需要调用它。
标题文件:
#import <UIKit/UIKit.h>
@interface TST_ViewController : UIViewController
+ (NSString *) applicationDocumentsDirectory;
@end
实施档案:
#import "TST_ViewController.h"
@interface TST_ViewController ()
@end
@implementation TST_ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *dbFilename = @"db.sql";
NSString *userPath = [[TST_ViewController applicationDocumentsDirectory] stringByAppendingPathComponent:dbFilename];
NSString *srcPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbFilename];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL foundInBundle = [fileManager fileExistsAtPath:srcPath];
BOOL foundInUserPath = [fileManager fileExistsAtPath:userPath];
BOOL copySuccess = FALSE;
NSError *error;
if(foundInBundle) {
if (!foundInUserPath) {
NSLog(@"Don't have a writable copy, so need to create one...");
copySuccess = [fileManager copyItemAtPath:srcPath toPath:userPath error:&error];
}
if (!copySuccess) {
NSLog(@"Failed with message: '%@'.",[error localizedDescription]);
}
} else {
// handle error in the event the file is not included in the bundle
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
@end