我对 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 行)行之后在设备中进行测试时崩溃;但在模拟器中效果很好。
非常感谢普拉卡什