마음심기 프로젝트에서 마음들을 CoreData에 저장하기로 결정했다.
근데 이제 CoreData를 이용한 로직들에 대해 테스트까지 겸한..! (TDD로 짜보겠다고 노력하고 있는데 과연 잘 하고 있는지 모르겠군..)
CoreData 사용
file 생성할 때 Data Model 선택한 후 생성
ENTITIES 생성한 뒤 해당 엔티티에 필요한 attribute 추가
final class CoreDataStack: ObservableObject {
let persistentContainer: NSPersistentContainer
init(_ storageType: StorageType = .persistent) {
self.persistentContainer = NSPersistentContainer(name: "MoodRecords")
// test setup
if storageType == .inMemory {
let description = NSPersistentStoreDescription(url: URL(filePath: "dev/null"))
self.persistentContainer.persistentStoreDescriptions = [description]
}
self.persistentContainer.loadPersistentStores { _, error in
if let error {
fatalError("Failed to load persistent stores: \(error.localizedDescription)")
}
}
}
}
그 후 CoreDataStack 파일 추가.
Testable한 코드를 위해 storage type을 받도록 함. (테스트 시에는 inMemory로 사용해 메모리에 저장한다.)
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext,
coreDataStack.persistentContainer.viewContext)
}
}
앱 시작 코드에서 .managedObjectContext에 CoreDataStack의 viewContext를 지정.
(CoreDataStack을 @StateObject private var coreDataStack = CoreDataStack()로 생성해주었다.)
CoreData의 optional과 Swift의 optional은 다른 것이었다....
attribute의 optional 속성을 체크 해제해주었는데 왜 CoreDataProperties에 들어가면 해당 속성이 optional로 나오는지 의문이었던 찰나에 찾게된 블로그.
coredata의 optional은 새로 변경할 값이 optional일 수 있다는 의미였다고 한다. (swift는 초기화부터 optional일 수 있다느 의미고..)
그래서 CoreDataProperties 값을 직접 관리할 수 있도록 Entity의 codegen을 manual로 설정해주었다.
그 이후에 Editor - Create NSManagedObject Subclass를 눌러주면 CoreDataProperties와 CoreDataClass가 나온다.
non-nil이어야 하는 프로퍼티들에서 Optional을 제거해주었다. + 크래시 방지를 위해 Default 값도 지정해주었음.
TC도 추가해놨으니 이제 진짜 뷰모델 로직 짜면 되겠다!
참고 사이트
https://developer.apple.com/documentation/coredata/setting_up_a_core_data_stack
https://www.donnywals.com/setting-up-a-core-data-store-for-unit-tests/
https://phillip5094.tistory.com/14
'SwiftUI > Planting-Mind Dev Log' 카테고리의 다른 글
devlog 06. SwiftUI - FileImporter, FileExporter (0) | 2024.04.09 |
---|---|
devlog 05. Scheme '__' is not currently configured for the test action. (0) | 2024.03.21 |
devlog 04. Localization with String Catalog (0) | 2024.03.13 |
devlog 03. sink에 들어오는 값은 willSet의 값이었다. (0) | 2024.03.12 |
devlog 02. github action 세팅하기 (Feat. github action에서 xcresult 확인하는 법) (0) | 2024.03.04 |