OGeek|极客世界-中国程序员成长平台

标题: ios - 在 iOS 中使用 Core Data 提供初始数据 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:15
标题: ios - 在 iOS 中使用 Core Data 提供初始数据

这就是我需要的:使用我在 iPhone 模拟器上创建的示例实体填充一个 sqlite 文件,然后在应用程序最初为我的所有用户运行时复制该文件。

我做了什么:

  1. 我在模拟器中创建了一堆条目。

  2. 我在 MAC 上的 iPhone Simulator iOS 文件夹中找到了附加到我的应用程序的 sqlite 文件。

  3. 从 .sqlite、.sqlite-shm、.sqlite-wal 这三个文件中,我只是将 .sqlite 文件复制到了我的 xCode 项目中。

  4. 当我运行应用程序时,.sqlite 文件显示为空!

我该如何解决这个问题?

谢谢!

编辑:

.sqlite-wal 和 .sqlite-shm 有什么意义?

为什么它们存在,为什么在 iOS7 之前不存在?



Best Answer-推荐答案


你需要这样的东西:

- (void)copyPreparedDatabase{
    __persistentStoreCoordinator = nil;

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent"DATABASE.sqlite"];
    NSString *storePath = [storeURL path];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource"DATABASE" ofType"sqlite"];
    if (defaultStorePath) {
        NSError *error = nil;

        if ([fileManager fileExistsAtPath:storePath]) {
            [fileManager removeItemAtPath:storePath error:&error];
        }
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:&error];

        NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
        if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:storePath error:&error]) {

        }
    }
}

然后你从 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator 调用它 AppDelelate.m

建议:做一些自定义开关,例如 #define IMPORT_PREPARED_DATABASE

这样做: if (![fileManager fileExistsAtPath:storePath] && !IMPORT_PREPARED_DATABASE) {//&& 1==2 [自复制PreparedDatabase];
}

所以你可以控制何时构建新的准备好的数据库或何时使用现有的....

注意: 当你建立新的准备好的数据库sto模拟器时,复制数据库并将其粘贴到旧的......

关于ios - 在 iOS 中使用 Core Data 提供初始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862270/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4