1

我对 iOS 应用程序开发很陌生。

我正在尝试构建一个示例数据库应用程序,它将记录保存到数据库并从中获取。

当我使用模拟器进行测试时,该应用程序运行良好。我已经创建了一个本地数据库,并且我在需要时以编程方式制作了它的副本。我还检查了“复制捆绑资源”中是否引用了本地数据库。

但我得到的错误是,“ * 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'* -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'”。

我认为导致此问题的代码是“ [FileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil]; ”

它对模拟器非常有用,但当我用我的设备进行测试时就不行了。

期待帮助。

我的代码是,

- (id)init {

    self = [super init];

    //Datbase Name
    DBName=@"Person.sqlite3";

    //Getting DB Path
    NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDir = [documentsPath objectAtIndex:0];

    DBPath=[documentsDir stringByAppendingPathComponent:DBName ];
    //DBPath = [[NSString alloc] initWithString: [documentsDir stringByAppendingPathComponent:DBName]];
    NSLog(@"DBPath is  %@",DBPath);

    return self;

}


-(void)checkAndCreateDB{

    BOOL Success;

    //NSFileManager maintains File
    NSFileManager *FileManager = [NSFileManager defaultManager];
    NSLog(@"line 1");

    //Checks Database Path
    Success = [FileManager fileExistsAtPath:DBPath];
    NSLog(@"line 2");

    //If file exists, it returns true
    if(Success)return;
    NSLog(@"line 3");

    //NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName];

    // Get the path to the database in the application package
    NSString *databasePathFromApp=[[NSBundle mainBundle] pathForResource:@"Person.sqlite3" ofType:@"sqlite3"];
    NSLog(@"line 4");

    [FileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil];
    //[FileManager release];
    NSLog(@"line 5");

}

我的应用程序在 NSLOG(第 4 行)行之后在设备中进行测试时崩溃;但在模拟器中效果很好。

非常感谢普拉卡什

4

2 回答 2

0

设备无法写入 app bundle,需要使用 Documents 目录。

以下是获取 Documents 目录路径的方法:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

如果您在应用程序包中有初始数据库,则在初始启动时将其复制到 Documents。

于 2012-01-16T02:51:35.427 回答
0

更改此行

NSString *databasePathFromApp=[[NSBundle mainBundle] pathForResource:@"Person.sqlite3" ofType:@"sqlite3"];

NSString *databasePathFromApp=[[NSBundle mainBundle] pathForResource:@"Person" ofType:@"sqlite3"];

另外,注意大小写,iOS设备区分大小写,而在模拟器上,你会得到错误的大小写

于 2012-01-16T03:42:20.343 回答