我使用“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数据库浏览器”给它创建的文件的扩展名。 。)
答案 0 :(得分:28)
答案与确保正确设置sql文件的“目标成员资格”有关,以便项目“看到”它:
1)单击Xcode左窗格中的sql文件
2)打开/显示文件检查器(右窗格)
3)在“目标会员资格”下,确保“检查”是“已检查”
就是这样。
答案 1 :(得分:2)
这个解决方案解决了我的问题,希望它能帮到你。
答案 2 :(得分:0)
在我的问题中: 检查这一行:
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"users.sql"]
检查捆绑包和代码中的fileName - 错误也是由不同的文件名引起的。