11

I created an sql database using "SQLite Database Browser", dragged and dropped it into my Xcode project, and built the app. It works perfectly well on the Simulator but crashes on the iPhone, with this error:

*** 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.)'.'   

Here's my code:

- (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;
}

Again, this works on the Simulator, but not on the iPhone. (This couldn't possible have anything to do with the file have a ".sql" extension as opposed to a ".sqlite" extension, could it? Cause that's the extensions that "SQLite Database Browser" gives the files it creates...)

4

3 回答 3

28

答案与确保正确设置 sql 文件的“目标成员资格”有关,以便项目“看到”它:

1)点击Xcode左侧窗格中的sql文件

2)打开/显示文件检查器(右窗格)

3)在“目标会员”下,确保“检查”是“检查”

而已。

于 2012-04-30T13:03:03.933 回答
2

在此处输入图像描述

该解决方案解决了我的问题,希望对您有所帮助。

于 2014-04-21T12:11:57.140 回答
0

在我的问题中:检查这一行:

NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"users.sql"]

检查您的包和代码中的文件名 - 错误也与不同的文件名有关。

于 2012-10-02T06:11:50.953 回答