컴퓨터언어/Swift

[Swift] Core Data

bbanpro 2020. 4. 20. 01:22
728x90
반응형
DB용어 Core Data
table(relation), class entity
attribute(property), column attribute
record(tuple), row NSManagedObject

 

Core Data는 데이터베이스 방식이다.

 

DB에 여러 개의 테이블이 있다면, Core Data에서는 테이블을 Entity라고 부른다.

DB를 SQLite 같은 DBMS에서 테이블 관계를 관리하는 것처럼, Core Data에는 Persistent Container 에서 테이블들을 모으고, Context가 User와 통신하며 자료 간 관계를 설정한다.

 

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

UIApplication.shared.delegate는 현재 실행중인 App의 AppDelegate.swift 파일에 접근하는 Singleton이다.

 

우리는 Context로 CRUD 작업을 할 수 있으며,

try context.save() 로 확정하기 전까지 얼마든지 검토와 실행취소를 할 수 있다.(git에서 commit하기 전과 비슷)

 

즉 Context는 User의 요청을 받은 App이 Persistent Container에 접근하는 것을 도와주는 중간다리다.

// 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: "DataModel")
        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)")
            }
        }
    }

Core Data는 로컬 디스크 속 고유 디렉토리에 미로처럼 자리잡아 sqlite파일로 저장된다.

우리가 설정한 Entity 이름은 클래스를 인스턴스화 하듯이 swift 파일에서 생성할 수 있으며,

Entity 안에 있는 Attribute들 역시 자동으로 따라서 생성된다.

 

Nil이 되지 않도록 Attribute에 값을 넣어주는 것 조심하자.

728x90
반응형