在应用程序中运送预先填充的SQLite DB。启动时DB的路径

时间:2011-11-15 21:45:48

标签: iphone ios sqlite core-data persistent-storage

问题的标题可能不是很明显,但我不知道如何总结。

我正在完成一个基本上是数据库的应用程序。我将在App中发布数据库。一切都运作良好,但现在我遇到了问题。安装App后,需要在设备上创建数据库。所以,我将数据库拖到我的Xcode项目中的“Supporting Files”文件夹中(顺便说一下,仍然是Xcode 4.1)。我转到AppDelegate.m文件并查找(NSPersistentStoreCoordinator *)persistentStoreCoordinator {}方法。

我换了一行:

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Database.sqlite"];

代码:

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Database.sqlite"];
NSLog(@"%@", storePath);

NSURL *storeURL = [NSURL fileURLWithPath:storePath];

    // Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Database" ofType:@"sqlite"];
    if (defaultStorePath) {
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
    }
}

我是从a tutorial by Ray Wenderlich得到的。

问题是编译器在行上给了我一个警告

NSString * storePath = [[self applicationDocumentsDirectory] ​​stringByAppendingPathComponent:@“Database.sqlite”];

告诉我“NSURL可能没有响应'stringByAppendingPathComponent',实际上,App因此而崩溃。有趣的是,教程中的示例没有给出任何警告。

有人可以帮我解决一下我缺少的东西吗?

提前致谢!

1 个答案:

答案 0 :(得分:2)

你确定[self applicationDocumentsDirectory]返回一个NSString吗?如果没有,试试这个

- (NSString *)applicationDocumentsDirectoryString {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

将[self applicationDocumentsDirectory]更改为[self applicationDocumentsDirectoryString]