티스토리 뷰
Core Data 에러 : No NSEntityDescriptions in any model claim the NSManagedObject subclass
Larooly 2025. 6. 19. 01:52안녕하세요.
요즘 저장소에대해 여러가지 실험한다고 했다가
에러가 나와서 데려왔습니다.
그리하여 간만에 오류 박제
발생 상황
Core Data 를 사용해보려고 열심히 설정 다하고 코드를 만들었는데 아래 같은 오류가 뜨면서 아예 정지됩니다. 흑...
오류 내용
CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'Entity 이름' so +entity is confused. Have you loaded your NSManagedObjectModel yet ?
원인
저게 무슨 말인가 했는데 제가 기존 프로젝트 중간에 Core Data 를 추가한거다보니 생긴거라고 합니다.
(보통 프로젝트 생성할때 Core Data 사용 체크하면 발생 X)
조금 더 간단히 이야기하면 제가 선언한 Entity 가 어느 파일에 선언된 친구인지 모르겠다고
Xcode 에서 투덜거리는거라고 생각하시면됩니다.
만약 초기 생성할때 Core Data 사용한다고 체크하면 알아서 AppDelegate 에 무언가 생긴다고 하네요.
근데 우린 그게 아니니까 파일 이름을 코드로 알려주면 됩니다.
해결 방법
그럼 자동으로 생성하는 친구는 뭘 만들어주는지만 알면 따라서 만들어 줄 수 있겠네요.
실제로 해보면 기존 AppDelegate 클래스에 뭔가 잔뜩 주석이랑 만들어졌습니다.
import UIKit
import CoreData
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "TestAutoCoreData")
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)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
기...길다....
전체는 더보기 누르시면 보이는데 요약해서 보여드리면 주석만 길지 별 내용 없습니다.
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: ".xcdatamodeld파일이름")
// 파일명으로 변경해야합니다.
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
이걸 현재 사용하는 프로젝트의 AppDelegate.swift 에 클래스 안에 그대로 넣어주세요.
그럼 이제 기존에 제가 사용하려던 코드쪽으로 돌아와서
기존에 에러난 코드 (Before)
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
수정 코드 (After)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
후후 드디어 성공했습니다.
처음엔 context 가 그래서 뭔 역할이지 했는데 Entity가 들어있는 파일을 설정하고 저장도 해주고
여러 일을 하는 도우미였군요
Core Data 를 처음 다루시는 분들에게
도움이 되었으면 좋겠습니다.
(+me...)
아무튼 오늘도 파이팅입니다.
'iOS개발 > 기타' 카테고리의 다른 글
Xcode 'iostream' file not found 에러 (0) | 2025.03.27 |
---|---|
[실험] C++을 Xcode 에서 적용해보자 (ObjC/Swift) (0) | 2025.03.27 |
Called object type 'Class' is not a function or function pointer 에러 (0) | 2025.03.25 |
[실험실패].a 파일 xcframework 변환 및 PrivacyInfo 추가하기 (0) | 2025.03.17 |
Xcode '앱이름'을(를) 설치할 수 없음 문제 (0) | 2025.01.17 |