https://minsub12004.tistory.com/53
CoreData와 객체그래프 - 1
CoreData는 애플이 제공해주는 객체 그래프 및 영속성 프레임 워크 입니다. iOS나 macOS 등에서 앱 데이터를 저장하고 관리하는데 사용합니다. 데이터베이스와 같이 데이터를 영구저장 할 수 있으
minsub12004.tistory.com
CoreData는 객체 그래프 관리와 관계 데이터 모델링에 강점이 있는 객체 지향 데이터 관리 시스템 입니다.
주요 요소
NSManagedObject: CoreData에서 데이터 객체는 NSManagedObject 로 생성됩니다
NSManagedObjectContext: 모든 데이터 작업의 트랜잭션을 관리하며, 데이터를 실제로 생성, 수정, 삭제, 저장하는 역할을 합니다.
Persistent Store Coordinator: 데이터 저장소와의 통신을 관리하며, 데이터를 실제로 보관할 저장소를 관리하는 역할입니다. SQLite, Binary, In-Menory 저장소 중 하나를 선택하여 데이터를 보관할 수 있습니다.
위의 내용은 이 전 포스트에 좀 더 자세히 적혀있으니 참고 바랍니다.
프로젝트에 Core Data 설정하기
XCode에서 새로운 프로젝트를 만들 때 iOS 에 앱을 선택하면 이런 화면이 나옵니다.
Storage에서 Core Data 를 선택해주고 프로젝트를 만들어주면 CoreData 가 기본 설정되게 됩니다
프로젝트를 생성하면 기본적으로 생성되는 파일중에
Persistence.swift 라는 파일이 존재합니다.
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
@MainActor
static let preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
}
do {
try viewContext.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)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "_234")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
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)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
해당 소스코드를 보면
PersistenceController
라는 클래스가 CoreData 스택을 설정하고 관리하는 역할을 하고 있습니다.
NSPersistentContainer
위의 클래스는 CoreData 스택을 설정하고 관리합니다.
이를 통해 저장소를 초기화하고 NSManagedObjectContext 에 접근이 가능합니다.
let context = PersistenceController.shared.container.viewContext
위의 코드와 같이 PersistenceController.shared 를 사용하여 컨텍스트를 가져와서
CoreData 작업을 수행 가능합니다.
모델생성
CoreData에서 사용할 엔티티는 데이터 모델 파일(.xcdatamodeld)를 통해 정의 가능합니다.
프로젝트 안에 있는 .xcdatamodeld파일을 클릭합니다.
파일을 열면 이렇게 나옵니다.
아래의 Add Entity 를 선택하여 User라는 엔티티를 추가합니다.
엔티티를 추가하게 되면 Attribute 에서 엔티티의 속성을 추가할 수 있습니다.
저는 예시로 name 이라는 String 타입의 속성을 추가하였습니다.
만약 엔티티간 관계를 설정하고 싶으면
Relationships 섹션에서 새로운 관계를 추가하고, 다른 엔티티와 연결을 설정 가능합니다.
데이터 저장 코드 예제
import SwiftUI
import CoreData
struct ContentView: View {
let context = PersistenceController.shared.container.viewContext
var body: some View {
VStack {
Button(action: {
saveData(name: "Sample User")
}) {
Text("유저 저장")
}
}
}
func saveData(name: String) {
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)!
let newUser = NSManagedObject(entity: entity, insertInto: context)
newUser.setValue(name, forKey: "name")
do {
try context.save()
print("데이터 저장 성공!")
} catch {
print("데이터 저장 실패: \(error)")
}
}
}
위의 코드는 PersistenceController.shared 를 통하여 NSManagedObjectContext 를 가져오는 코드 입니다.
해당 코드의
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)!
let newUser = NSManagedObject(entity: entity, insertInto: context)
해당 부분은 "User" 엔티티의 새로운 객체를 생성하는 부분의 코드 입니다.
newUser.setValue(name, forKey: "name")
해당 부분은 객체에 데이터를 설정하는 코드 입니다.
do {
try context.save()
print("데이터 저장 성공!")
} catch {
print("데이터 저장 실패: \(error)")
}
데이터를 저장하는 코드 입니다.
데이터 불러오기
데이터를 불러오려면 NSFetchRequest 를 사용하여 데이터를 불러올 수 있습니다.
func fetchData() {
let request = NSFetchRequest<NSManagedObject>(entityName: "User")
do {
let users = try context.fetch(request)
for user in users {
if let name = user.value(forKey: "name") as? String {
print("User Name: \(name)")
}
}
} catch {
print("데이터 불러오기 실패: \(error)")
}
}
NSFetchRequest를 사용하여 User 엔티티에서 모든 데이터를 불러오고 각각의 이름을 출력할 수 있습니다.
'swift 복습' 카테고리의 다른 글
의존성 주입 (0) | 2024.11.17 |
---|---|
CoreData와 객체그래프 - 1 (5) | 2024.11.10 |
Unit test (0) | 2024.10.11 |
Combine의 개념 (0) | 2024.10.06 |
MVVM 디자인 패턴 (0) | 2024.09.22 |