iOS/코드조각

[iOS, Swift] CoreData 초기 설정 안 해주었을 시 수동 설정방법

검은참깨두유vm 2022. 12. 10. 17:53
반응형

iOS 16.1, Xcode 14.1, Swift 5, UIKit 환경에서 진행했습니다.

 

1. 프로젝트에 DataModel 파일을 추가합니다.

 

2. AppDelegate.swift 파일에 CoreData 라이브러리를 import 합니다.

import CoreData

 

3. AppDelegate.swift 파일에 코드를 넣습니다.

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "DataModel")
    container.loadPersistentStores {
        if let error = $1 as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    }
    return container
}()

func saveContext() {
     let context = persistentContainer.viewContext
     if context.hasChanges {
         do {
             try context.save()
         } catch let error as NSError {
             fatalError("Unresolved error \(error), \(error.userInfo)")
         }
     }
 }
 
 func applicationWillTerminate(_ application: UIApplication) {
     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
     self.saveContext()
 }

 

반응형