'Failed to find a unique match for an NSEntityDescription CoreData Swiftui
When I use my app, sometimes, I have an error that appear, it seems to be randomly (or I didn't figure out when exactly...), then all my lists are empty (like if nothing were in CoreData). But If I close my app and re-open it, lists appear without any problem...
I searched on stack overflow about this problem, but nothing is clear for me...
Error :
CoreData: warning: 'CDDetail' (0x2815e8790) from NSManagedObjectModel (0x2841bb8e0) claims 'CDDetail'.
2020-11-13 19:16:48.329773+0100 OrientationEPS[33705:3479327] [error] error: +[CDDetail entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
CoreData: error: +[CDDetail entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
Loading the persistent Container :
class OriEPS {
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "OrientationEPS")
container.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
return container
}()
var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
And Here is my function to fetch the result :
private func fetchCDDetail(withId detailId:UUID) -> CDDetail? {
let fetchRequest = NSFetchRequest<CDDetail>(entityName: "CDDetail")
fetchRequest.predicate = NSPredicate(format: "id == %@", detailId as CVarArg)
fetchRequest.fetchLimit = 1
let fetchResult:[CDDetail]? = try? context.fetch(fetchRequest)
return fetchResult?.first
}
2 questions : How should I solve this error ? What does mean 0x2815e8790 ?
Edit 1 : I can't find any other class call CDDetail
- If I set Module to Current Product Module (nothing change)
- Nothing change If I replace :
- fetchRequest:NSFetchRequest = CDDetail.fetchRequest()
by
- fetchRequest = NSFetchRequest(entityName:"CDDetail")
Solution 1:[1]
You loaded model several times - that's the reason of those errors. Possible solution is to make container static.
Tested with Xcode 12.1 / iOS 14.1 - no errors:
class OriEPS {
private static var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CDOriEPS")
container.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
return container
}()
var context: NSManagedObjectContext {
return Self.persistentContainer.viewContext
}
// ... other code
Note: other possible approach is to make OriEPS
shared and use same instance everywhere you create it, but I did not investigate your solution deeply, so it is for your consideration.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |