ios - 无法访问核心数据文件

标签 ios swift core-data realm realm-mobile-platform

我有一个完全基于 Objective C 的应用程序,它使用核心数据。我用 swift 重写了完整的应用程序,现在使用 Relam 进行 swift 应用程序。当用户从 Objective C 升级到 swift 应用程序时,我想将一些数据库从核心数据迁移到 Realm。但我无法访问核心数据文件。

两个应用程序具有相同的 bundle 标识符。

Objective C version:
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"StoreName" withExtension:@"momd"];

Swift Version:
    let url = Bundle.main.url(forResource: "StoreName", withExtension: "momd")

最佳答案

如果您使用的是 ios 10 以上版本,请按照以下方法操作

  lazy var persistentContainer: NSPersistentContainer = {
                 let container = NSPersistentContainer(name: "StoreName")
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                      })
            return container
        }()

使用以下方法获取上下文

  func context() -> NSManagedObjectContext {
        if #available(iOS 10.0, *) {
            return persistentContainer.viewContext
        } else {
            // Fallback on earlier versions
            return managedObjectContext
        }
    }

关于ios - 无法访问核心数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339573/

相关文章:

iphone - 在 ios6 中从 iPhone 相机捕获全景图像

swift - Collectionview Reloaddata 函数不工作

sqlite - 使用 NSPersistentContainer 从 Core Data SQLite 存储回收空间?

ios - tableView.reloadData 清除数组 - 索引超出范围

swift - CGRect 不与渐变子层一起出现

ios - 如何拆除核心数据堆栈?

ios - 自定义 CoreData 访问框架而不是 AppDelegate

iphone - UITableViewCell 中 UILabel 文本的位置

ios - 如何在 ios swift 中添加彩色图标?

ios - 对表格 View 单元格(包括标题)进行动画处理