Xcode报错:Multiple NSEntityDescriptions claim the NSManagedObject subclass ‘ERdepot.CryptoCurrency’ so +entity is unable to disambiguate.
Xcode报错:Multiple NSEntityDescriptions claim the NSManagedObject subclass ‘ERdepot.CryptoCurrency’ so +entity is unable to disambiguate.

Xcode报错:Multiple NSEntityDescriptions claim the NSManagedObject subclass ‘ERdepot.CryptoCurrency’ so +entity is unable to disambiguate.

问题描述

在添加Core Data相关代码后,运行Xcode项目提示如下报错:

warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'ERdepot.CryptoCurrency' so +entity is unable to disambiguate.
CoreData: warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'ERdepot.CryptoCurrency' so +entity is unable to disambiguate.
...
error: +[ERdepot.CryptoCurrency entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
CoreData: error: +[ERdepot.CryptoCurrency entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
*** First throw call stack:
(0x1a7c9cf20 0x19fb432b8 0x1afd97c94 0x1afe3d9f4 0x1afd8dfe8 0x1afe04124 0x1abe60294 0x1abe0c860 0x1abe1861c 0x104951204 0x104951734 0x1cb443154)
libc++abi: terminating due to uncaught exception of type NSException

根据报错的信息,了解到有多个 CryptoCurrency 实体在 Core Data 的模型中指向了同一个 NSManagedObject 子类 ERdepot.CryptoCurrency,导致系统不知道该用哪个。最终导致 @FetchRequest 无法解析出该用哪个实体,结果抛出异常崩溃。

问题原因

当我根据报错信息了解到是@FetchRequest的原因后,我将刚刚添加的@FetchRequest代码隐藏后,报错消失并且可以安装、运行应用。

// 使用 @FetchRequest 获取数据
//        @FetchRequest(
//            sortDescriptors: [NSSortDescriptor(keyPath: \CryptoCurrency.marketCapRank, ascending: true)],
//            animation: .default)
//        private var cryptoCurrencys: FetchedResults<CryptoCurrency>

我在对比的过程中,发现我的这个@FetchRequest的代码写法有问题,与我前面正常的@FetchRequest代码不同。

@FetchRequest(
    fetchRequest: {
        let request = NSFetchRequest<CryptoCurrency>(entityName: "CryptoCurrency")
        request.sortDescriptors = [NSSortDescriptor(keyPath: \CryptoCurrency.marketCapRank, ascending: true)]
        return request
    }()
) var cryptoCurrencys: FetchedResults<CryptoCurrency>

之前正常的@FetchRequest是这样的。

当我将 @FetchRequest 修改为之前正常的样式时,问题得到解决。

总结

没有想到这个问题竟然是@FetchRequest造成的,我尝试清理构建文件夹和DerivedData文件夹,仍然不起作用。

在将@FetchRequest修改为之前的样式后,问题猜得到解决。

这个报错的@FetchRequest代码还是从我之前学习Core Data的文章中复制过来的,真是误人子弟啊,现在已经将Core Data文章中的这个代码修复成功。

相关文章

Apple Core Data持久化框架:https://fangjunyu.com/2025/03/30/apple-coredata%e6%8c%81%e4%b9%85%e5%8c%96%e6%a1%86%e6%9e%b6/

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注