코어데이터를 사용할때 Failed to find a unique match for an NSEntityDescription to a managed object subclass
에러가 발생할때가 있다.
해당 에러는 coredata의 container 여러개 생성 했을때 발생된다.
여기서 container는 NSPersistentConter
로 생성되는 객체를 말한다.
보통 프로젝트를 생성하면 Persistence.swift
파일에 container를 선언 해둔다.
이 상태로 다른 코드에서 새로운 container를 생성하고 사용하면 위와 같은 에러가 발생된다.
해당 에러를 해결하기 위해서 하나의 container만 사용하면 된다.
PersistenceController.swift 코드
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "project") // container 생성
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
// container.viewContext.automaticallyMergesChangesFromParent = true
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
CoreDataViewModel 코드
class CoreDataViewModel: ObservableObject {
let managedObjectContext = PersistenceController.shared
let container: NSPersistentContainer
init() {
container = NSPersistentCloudKitContainer(name: "project")
container.loadPersistentStores { description, error in
if let error = error {
print("ERROR LOADING CORE DATA")
print(error.localizedDescription)
} else {
print("SUCCESSFULLY LOAD CORE DATA")
}
}
}
...
}
위의 예시 코드를 보면 Persistencse.swift
에서 container를 생성한다.
그리고 CoreDataViewmodel.swift
의 초기화 함수에서 또 container를 생성한다.
이렇게 중복생성된 container를 사용할때 해당 에러가 발생한다.
여기서 해당 문제를 해결하기 위해 초기에 선언된 container를 계속 사용하면된다.(또는 나중에 다른곳에서 생성된거를 계속 사용해도 된다.)
PersistenceController.swift 코드는 그대로 유지
CoreDataViewModel 코드
class CoreDataViewModel: ObservableObject {
let container: NSPersistentContainer = PersistenceController.shared.container
init() {
...
}
...
}