0

我一直在为 iPhone 编写这个应用程序,我需要使用 sqlite。我已经用一堆数据预加载了我的 sqlite,我将该 sqlite 文件复制到我的项目文件夹中。当我启动应用程序时,似乎 sqlite 数据文件没有复制到模拟器的应用程序文件(文档位置)。这是我的代码:

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"moviedbl.data"];
    BOOL success = [fileManager fileExistsAtPath:dbPath];

    if(!success){
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: @"moviedbl.data"];
        //NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"moviedbl" ofType: @"data"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if(!success){
            NSAssert1(0, @"Failed to create writable database file with message '%'.", [error localizedDescription]);
        }
    }

貌似defaultDBPath是指模拟器中的app文件夹,原本不包含任何sqlite文件,实际上是在等待一个sqlite文件被复制到里面。据我了解,要复制文件,我们应该从我们的包中获取文件(不确定包是指我们的项目文件夹还是什么,但我认为它是我们的项目文件夹)并将其复制到我们的模拟器。我已经坚持了好几天了,请赐教... 非常感谢您提前!!!

更新:所以我真的让它工作了。起初我以为是因为我没有从 mainBundle 或其他东西中复制文件,但事实证明,当我打开路径中 .app 的实际文件夹时,我做到了。我看到它实际上包含的数据库。奇怪的是它没有文件类型,但在 xCode 中它将文件类型显示为“数据”,所以我一直使用 ofType:@“数据”。所以最后我把它改成了 ofType:@"" 并且成功了!无论如何!愚蠢的我,但感谢所有试图帮助的人!:D

4

1 回答 1

1
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];

NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"moviedbl.data"];

if([fileManager fileExistsAtPath:dbPath]==NO){

    NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"moviedbl" ofType: @"data"];
   BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

    if(!success){
        NSAssert1(0, @"Failed to create writable database file with message '%'.", [error localizedDescription]);
    }
}
于 2012-06-06T09:51:45.873 回答