【发布时间】:2011-07-03 11:43:51
【问题描述】:
我正在自学 Objective-c,目前正在尝试研究如何将数据库集成到我的应用程序中。我查看了许多示例、论坛和教程,但没有一个有效,我做错了什么?
大多数示例在应用程序中都带有 [projectName].sqlite 数据库。它是如何添加的?没有看到关于如何在项目中结束的解释。
我已经创建了我的对象模型和类。我正在运行一个检查数据库是否存在的方法,如果不存在,它会创建数据库。我发现了几个使用不同路径的示例,但我不确定哪个是正确的,一些示例将我的项目文件的一部分复制到了文档/mainDatabase.sqlite 文件夹中!以下是否正确,如果是,为什么我会收到错误消息?
* 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法创建带有消息的可写数据库文件”操作无法完成。没有这样的文件或目录。
使用这些会导致上述错误,是的,defaultDBPath 确实存在
默认数据库路径: /Users/myuser/Library/Application Support/iPhone Simulator/4.2/Applications/DFBAD921-CEBF-471E-B98B-04FDF2620146/Documents
默认数据库路径: /Users/myuser/Library/Application Support/iPhone Simulator/4.2/Applications/DFBAD921-CEBF-471E-B98B-04FDF2620146/Documents/mainDatabase.sqlite
可写数据库路径: /Users/myuser/Library/Application Support/iPhone Simulator/4.2/Applications/DFBAD921-CEBF-471E-B98B-04FDF2620146/dbProj12.app/mainDatabase.sqlit
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence - we don't want to wipe out a user's DB
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentDirectory = [self applicationDocumentsDirectory];
NSLog(@"documentDirectory = %@", documentDirectory);
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"iBountyHunter.sqlite"];
NSLog(@"defaultDBPath = %@", writableDBPath);
BOOL dbexits = [fileManager fileExistsAtPath:writableDBPath];
if (!dbexits) {
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"iBountyHunter.sqlite"];
NSLog(@"defaultDBPath = %@", defaultDBPath);
NSError *error;
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
}
期待您的回复。
【问题讨论】:
标签: objective-c xcode ipad sqlite