You need to enable JavaScript to run this app. 如何通过代码获取Core Data中persistentStoreDescriptions配置与实体的关联关系
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码获取Core Data中persistentStoreDescriptions配置与实体的关联关系

CoreData 配置与实体关联关系查询说明

结论

你要的关联关系可以通过苹果公开API直接查询,不属于未公开的内部实现。

具体查询方法

  • 查询所有自定义配置名:调用NSManagedObjectModel的configurations属性,可获取所有你在xcdatamodeld中定义的配置名称数组,示例中会返回["local", "memory"]。
  • 查询配置对应关联实体:调用NSManagedObjectModel的entities(forConfigurationName:)方法,传入配置名称即可返回该配置下包含的所有实体对象数组。
  • 查询配置是否适配CloudKit:iOS13+/macOS10.15+ 版本中,可直接读取NSPersistentStoreDescription的cloudKitContainerOptions属性,若属性不为空则代表该配置开启了CloudKit同步适配。

示例代码

// 直接通过NSPersistentContainer获取模型,也可单独加载本地模型文件
let container = NSPersistentContainer(name: "你的模型名称")

// 1. 获取所有配置名
guard let allConfigs = container.managedObjectModel.configurations else { return }
print("所有配置项:\(allConfigs)")

// 2. 遍历获取每个配置对应的实体
for configName in allConfigs {
    guard let entities = container.managedObjectModel.entities(forConfigurationName: configName) else { continue }
    let entityNameList = entities.compactMap(\.name)
    print("配置【\(configName)】包含实体:\(entityNameList)")
}

// 3. 判断配置是否适配CloudKit
let storeDesc = container.persistentStoreDescriptions.first
if storeDesc?.cloudKitContainerOptions != nil {
    print("当前存储配置开启了CloudKit同步")
}

内容的提问来源于stack exchange,提问作者Fatbobman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 16:21:03