[iOS] Core Data(2)

.onNext("Volga")·2023년 1월 12일
0

iOS

목록 보기
3/7

Setting Up a Core Data Stack

Set up the classes that manage and persist your app’s objects.

코어 데이터 스택을 설정하는 법에 대해 알아봅니다.

Overview

After you create a data model file as described in Creating a Core Data Model, set up the classes that collaboratively support your app’s model layer. These classes are referred to collectively as the Core Data stack.

코어 데이터 모델 만드는 방법에 따라서 데이터 모델 파일을 만든 후에는, 앱의 모델 계층을 collaboratively하게 지원하는 클래스를 set up하게 되는데 이러한 Class코어 데이터 스택 이라고 합니다.

An instance of NSManagedObjectModel represents your app’s model file describing your app’s types, properties, and relationships.

  • NSManagedObjectModel의 인스턴스는 앱의 model file, 유형, properties 및 관계를 설명하는 앱의 모델 파일을 나타냅니다.

An instance of NSManagedObjectContext tracks changes to instances of your app’s types.

  • NSManagedObjectContext 인스턴스는 앱의 유형의 인스턴스에 대한 변경사항을 추적하게 됩니다.

An instance of NSPersistentStoreCoordinator saves and fetches instances of your app’s types from stores.

  • NSPersistentStoreCoordinator 인스턴스는 저장소에서 앱 유형의 인스턴스를 저장하고 가져옵니다.

An instance of NSPersistentContainer sets up the model, context, and store coordinator all at once.

  • NSPersistentContainer 인스턴스는 모델, 컨텍스트 스토어 코디네이터를 한번에 설정합니다.

Initialize a Persistent Container

Persistent Container를 초기화 하는 것에 대해 알아봅니다.

Typically, you initialize Core Data during your app’s startup. Create the persistent container as a lazy variable to defer instantiation until its first use in your app’s delegate.

일반적으로 앱을 시작하는 동안 Core Data를 초기화 합니다.
앱의 Delegate에서 처음 사용할 때 까지 인스턴스화를 미루는 방식을 사용하기 위해 Persistent Containerlazy variable로 만들어서 사용하게 됩니다.

그래서 초기화 하는 과정을 간략하게 살펴보면,

Declare a lazy variable of type NSPersistentContainer.

  • NSPersistentContainer 타입의 lazy variable을 선언합니다.

Create a persistent container instance, passing the data model filename to its initializer.

  • persistent container 인스턴스를 생성해서 Data Model에 대한 filename을 이니셜라이저에 전달하게 된다.

Load any persistent stores. This call creates a store, if none exists.

  • persistent store를 로드하고 저장소가 없다면 호출을 통해 스토어를 생성하게 된다.
class AppDelegate: UIResponder, UIApplicationDelegate {

    ...

    lazy var persistentContainer: NSPersistentContainer = {        
        let container = NSPersistentContainer(name: "DataModel")
        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Unable to load persistent stores: \(error)")
            }
        }
        return container
    }()

    ...
}

위 처럼, 한번 persistent container가 생성되면 Model, Context, Store Coordinator 인스턴스에 대한 References가 각각 ManagedObjectModel, viewContext, persistentStoreCoordinator 속성에 지정하게 됩니다.

이렇게 되면, 이제 컨테이너에 대한 referenceUser Interface에 전달 할 수 있게 됩니다!

Pass a Persistent Container Reference to a View Controller

이제 CoreDataimport하게 되면 viewController 클래스에서 persistentContainer를 참조할 변수를 만들 수 있게 됩니다.

import UIKit
import CoreData

class ViewController: UIViewController {

    var container: NSPersistentContainer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        guard container != nil else {
            fatalError("This view needs a persistent container.")
        }
        // The persistent container is available.
    }
}

이 때, appDelegate으로 돌아가게 되면, application(_:didFinishLaunchingWithOptions:)에서, app window에 지정되어있는 rootViewController를 현재 앱에서 사용되는 root View Controller로 다운캐스팅해서 참조 값을 채워주게 됩니다.

class AppDelegate: UIResponder, UIApplicationDelegate {

    ...

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {        
        if let rootVC = window?.rootViewController as? ViewController {
            rootVC.container = persistentContainer
        }        
        return true
    }

    ...
}

또한 persistent container를 다른 viewController에 전달하려면 각 뷰 컨트롤러에서 Container를 담을 변수를 생성을 반복하고 이전 뷰 컨트롤러의 prepare(:sender:) 에서 해당 값을 설정 하면 됩니다.

class ViewController: UIViewController {

    ...
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let nextVC = segue.destination as? NextViewController {
            nextVC.container = container
        }
    }
}
profile
iOS 개발자 volga입니다~

0개의 댓글