Xcode报错:Failed to find a unique match for an NSEntityDescription to a managed object subclass
Xcode报错:Failed to find a unique match for an NSEntityDescription to a managed object subclass

Xcode报错:Failed to find a unique match for an NSEntityDescription to a managed object subclass

问题描述

在Xcode中进行真机调试应用,当点击下图的“管理外币”模块时,发生报错:

Xcode输出报错:

CoreData: error: +[ERdepot.UserForeignCurrency 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:
(0x18bfc0f20 0x183e672b8 0x1940bbc94 0x1941619f4 0x1940b1fe8 0x194128124

问题原因

根据《Issue with Core Data not finding the correct entity》文章的某个答案回复,了解到可能跟 @FetchRequest 有关。

因为报错的“管理外币”视图有使用 @FetchRequest,因此当因此设计 @FetchRequest 的代码后:

struct ForeignCurrencyView: View {
    @Environment(\.colorScheme) var color
    @EnvironmentObject var appStorage: AppStorageManager
    @Binding var isShowForeignCurrency: Bool
    @State private var textField: String = ""
    
    // 获取 Core Data 上下文
        @Environment(\.managedObjectContext) private var viewContext
        
//       @FetchRequest(
//           entity: UserForeignCurrency.entity(),
//           sortDescriptors: [NSSortDescriptor(keyPath: \UserForeignCurrency.symbol, ascending: true)]
//       ) var userForeignCurrencies: FetchedResults<UserForeignCurrency>
    ...
}

应用不再报错,并且可以点击进入到“管理外币”视图。

因此,目前推断报错跟 @FetchRequest 有关。

解决方案

可以使用NSFetchRequest明确指定实体:

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

通过手动告诉@FetchRequest 应该用那个实体,不需要SwiftUI自动尝试推断从Core Data中获取哪个实体。

总结

通过手动指定NSFetchRequest解决这一问题。

还发现一个类似的问题《Error when running a FetchRequest (Core Data, SwiftUI)》,这篇文章中博主反馈运行FetchRequest时出错。

最佳答案称,FetchRequest<NSFetchRequestResult>(entity…是一个属性包装器,它认为这个用法是无效的,这里有一个可能的解决方案,即直接使用CoreData NSFetchRequest,这似乎更适合在函数中使用。

与我们的解决方案类似,目前是全部的解答内容。

扩展知识

多个Core Data实体问题

在搜索文章的过程中,发现另一个类似的文章《CoreData: How to fix the “Multiple NSEntityDescriptions” problem》,这篇文章中有一个细节是:

This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.

翻译为:NSManagedObject此方法仅在调用代表模型中单个实体的子类时才是合法的。

该博主称,因为自己在模型中设置了多个实体,所以测试失败了,并且可能导致生产应用程序崩溃。

因此,这一问题可能也是本次报错的原因,就是当模型设置多个实体后,@FetchRequest的默认生产方法可能就会报错。

为了进一步验证这个问题,我将 @FetchRequest 替代为第一个创建的实体。

@FetchRequest(
    entity: Eurofxrefhist.entity(),
    sortDescriptors: [NSSortDescriptor(keyPath: \Eurofxrefhist.symbol, ascending: true)],
    predicate: nil  // 过滤条件
) var eurofxrefhist: FetchedResults<Eurofxrefhist>

使用Xcode连接iOS手机调试应用,Xcode仍然报错:

CoreData: error: +[ERdepot.Eurofxrefhist entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass

返回到 .xcdatamodeld 文件中。

删除 UserForeignCurrency 实体。

重新生成NSManagedObjectSubclass文件,仍然报错。

这也意味着,这个问题跟多个实体可能无关,仅有一个实体仍然会报错。

因此,这一问题不是多个Core Data实体的问题。

参考文章

1、Failed to find a unique match for an NSEntityDescription CoreData Swiftui:https://stackoverflow.com/questions/64826285/failed-to-find-a-unique-match-for-an-nsentitydescription-coredata-swiftui

2、Issue with Core Data not finding the correct entity:https://developer.apple.com/forums/thread/124656

3、SwiftUI获取Core Data数据的@FetchRequest:https://fangjunyu.com/2025/03/30/swiftui%e8%8e%b7%e5%8f%96core-data%e6%95%b0%e6%8d%ae%e7%9a%84fetchrequest/

4、Core Data获取数据的NSFetchRequest:https://fangjunyu.com/2025/04/10/core-data%e8%8e%b7%e5%8f%96%e6%95%b0%e6%8d%ae%e7%9a%84nsfetchrequest/

5、CoreData: How to fix the “Multiple NSEntityDescriptions” problem:https://medium.com/@jbrunhuber/coredata-how-to-fix-the-multiple-nsentitydescriptions-problem-205ebd281651

6、Core Data使用NSManagedObject Subclass管理数据:https://fangjunyu.com/2025/03/27/core-data%e4%bd%bf%e7%94%a8nsmanagedobject-subclass%e7%ae%a1%e7%90%86%e6%95%b0%e6%8d%ae/

7、Error when running a FetchRequest (Core Data, SwiftUI):https://stackoverflow.com/questions/63030450/error-when-running-a-fetchrequest-core-data-swiftui

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

发表回复

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