【问题标题】:Shipping a pre populated SQLite DB within the app. Path of the DB on startup在应用程序中提供预填充的 SQLite 数据库。启动时数据库的路径
【发布时间】:2011-12-29 22:11:16
【问题描述】:

也许问题的标题不是很清楚,但我不知道如何总结。

我正在完成一个基本上是数据库的应用程序。我将在应用程序中发送一个数据库。一切正常,但现在我遇到了问题。安装应用程序时,需要在设备上创建数据库。因此,我将 DB 拖到了我的 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',实际上,应用程序因此而崩溃。有趣的是,教程中的示例没有给出任何警告。

有人可以帮我解决我错过了什么吗?

提前致谢!

【问题讨论】:

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


    【解决方案1】:

    你确定 [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]

    【讨论】:

    • 好电话!它不是 NSString 而是 NSURL。我想知道他们为什么改变了这一点。无论如何,我已经尝试了您的建议,编译器没有给出错误,但在启动时崩溃:无法使用引导服务器注册 companyName.AppName。错误:未知错误代码。这通常意味着该进程的另一个实例已经在运行或挂在调试器中。当前语言:自动;目前objective-c
    • 好吧,没关系。我只是重置模拟器的问题。非常感谢斯科特!
    • 每当我进行重大更改时,为了安全起见,我都会进行干净的构建。并从模拟器/设备中删除应用程序。
    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多