我使用“SQLite 数据库浏览器”创建了一个 sql 数据库,将其拖放到我的 Xcode 项目中,然后构建了应用程序。它在模拟器上运行良好,但在 iPhone 上崩溃,出现以下错误:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Failed to create writable database file with message 'The operation could‚
not be completed. (Cocoa error 260.)'.'
这是我的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Creates a writable copy of the bundled default database in the application Documents directory:
NSLog(@"AppDelegate...Looking for embedded Database file...");
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
// Grab the path to the Documents folder:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"users.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) {
NSLog(@"Database File Exists in Documents folder!");
NSLog(@"Its path is: %@", writableDBPath);
return YES;
}
else {
// But if the writable database does not exist, copy the default to the appropriate location.
NSLog(@"!!NO Database File Exists in Documents folder!");
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"users.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
else
NSLog(@"WROTE THE DATABASE FILE!!!");
}
return YES;
}
同样,这适用于模拟器,但不适用于 iPhone。 (这不可能与具有“.sql”扩展名而不是“.sqlite”扩展名的文件有任何关系,对吧?因为这是“SQLite 数据库浏览器”为其创建的文件提供的扩展名.. .)
最佳答案
答案与确保正确设置 sql 文件的“目标成员身份”有关,以便项目“看到”它:
1) 点击Xcode左面板的sql文件
2) 打开/显示文件检查器(右 Pane )
3) 在“Target Membership”下,确保“check”为“checked”
就是这样。
关于iphone - 应用程序在尝试创建数据库时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378564/