[swift] 코어 데이터 스토어

코어 데이터는 애플의 iOS 및 macOS 앱에서 데이터를 관리하기 위한 강력한 프레임워크입니다. 코어 데이터는 여러 가지 데이터 모델을 정의하고, 데이터를 영구적으로 저장하고 검색할 수 있는 기능을 제공합니다. 이번 글에서는 Swift를 사용하여 코어 데이터 스토어를 설정하고 사용하는 방법에 대해 알아보겠습니다.

1. 프로젝트 설정

먼저, Xcode에서 프로젝트를 생성하고 코어 데이터를 사용할 준비를 해야합니다. 다음 단계를 따라 프로젝트를 설정하세요.

  1. Xcode를 열고 “새 프로젝트 생성”을 선택하세요.
  2. iOS 앱 템플릿을 선택하고 프로젝트 세부 정보를 입력하세요.
  3. “Core Data”를 선택하여 코어 데이터를 사용할 프로젝트로 설정하세요.
  4. 원하는 위치에 프로젝트를 저장하고 생성하세요.

2. 데이터 모델 생성

다음으로, 데이터 모델을 생성해야 합니다. 이 모델은 코어 데이터 스키마의 구조를 정의하는데 사용됩니다. 다음 단계를 따라 데이터 모델을 생성하세요.

  1. Xcode의 프로젝트 탐색기에서 .xcdatamodeld 파일을 선택하세요.
  2. “Editor” 메뉴에서 “Add Entity”를 선택하여 엔터티를 추가하세요.
  3. 엔터티에 원하는 속성을 추가하세요.
  4. 필요한 경우 관계를 설정하세요.
  5. 모델을 저장하세요.

3. 코어 데이터 스택 생성

이제 코어 데이터 스택을 생성해보겠습니다. 스택은 코어 데이터에 액세스하고 제어하기 위한 인터페이스 역할을 합니다. 다음 코드를 AppDelegate.swift 파일에 추가하세요.

import CoreData

class AppDelegate: UIResponder, UIApplicationDelegate {

    var persistentContainer: NSPersistentContainer!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        persistentContainer = NSPersistentContainer(name: "YourDataModelName")
        persistentContainer.loadPersistentStores { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        }
        return true
    }

    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)")
            }
        }
    }
}

주의할 점은 YourDataModelName은 프로젝트 탐색기에서 생성한 데이터 모델의 이름으로 변경해야 한다는 점입니다.

4. 데이터 추가/검색

이제 데이터를 추가하고 검색하는 방법을 알아보겠습니다. 데이터를 추가하는 코드는 다음과 같습니다.

func addData() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let entity = NSEntityDescription.entity(forEntityName: "YourEntityName", in: context)
    let newObject = NSManagedObject(entity: entity!, insertInto: context)

    newObject.setValue("John", forKey: "name")
    newObject.setValue(25, forKey: "age")

    do {
        try context.save()
    } catch {
        print("Failed to save data")
    }
}

데이터를 검색하는 코드는 다음과 같습니다.

func fetchData() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "YourEntityName")

    do {
        let results = try context.fetch(fetchRequest)
        for data in results {
            let name = data.value(forKey: "name") as! String
            let age = data.value(forKey: "age") as! Int
            print("Name: \(name), Age: \(age)")
        }
    } catch {
        print("Failed to fetch data")
    }
}

이제 코어 데이터 스토어를 설정하고 사용하는 방법에 대해 알게 되었습니다. 이를 기반으로 앱에서 데이터를 관리하고 검색하는 기능을 구현할 수 있습니다. 코어 데이터의 더 많은 기능을 알아보려면 공식 문서를 참조하세요.

참고 자료