• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 在 iOS 中使用 Core Data 提供初始数据

[复制链接]
菜鸟教程小白 发表于 2022-12-12 16:15:43 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

这就是我需要的:使用我在 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-推荐答案


  • 第一步 R OK,但随后你必须加载数据库

你需要这样的东西:

- (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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap