언어/스위프트 UI
[SwiftData] SwiftUI 프리뷰(Preview) 안될 때 처리방법
Psalm 23
2024. 4. 4. 05:52
#Preview
Xcode에서 CoreData, SwiftData를 Preview에서 보기 위해서는 @Query로 조회한 데이터를 사용할 수 없습니다. 이럴 때는 직접 데이터를 만들어서 테스트하는 방법이 있습니다.
우선 ModelConfiguration 객체를 인 메모리 only 행태로 생성합니다. 그리고 테스트 객체를 만들기 위해 ModelConfiguration 를 통해 ModelContainer를 만듭니다. 마지막으로 만들 때 사용할 모델을 추가해 줍니다.
그리고 이제 Preview에서 사용할 새로운 테스트 객체를 생성합니다. Container를 만들 config 객체는 isStoredInMemoryOnly를 true로 설정합니다.
#Preview(traits: .sizeThatFitsLayout) {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: FeedItem.self, configurations: config)
let feedItem = FeedItem(contents: "", type: .good)
return FeedItemCell(item: feedItem)
.frame(width: 340.0, height: 100.0)
.padding()
}
만약 배열형태의 데이터가 필요하다면 다음과 같이 처리할 수 있습니다.
#Preview {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: User.self, configurations: config)
for i in 1..<10 {
let user = User(name: "Example User \(i)")
container.mainContext.insert(user)
}
return ContentView()
.modelContainer(container)
}
처음 SwiftUI를 사용하면 Preview의 편리함을 알게 될 겁니다. 하지만 각종 environment 객체나 CoreData와 같은 데이터를 사용하면 점점 Preview Crash를 보게 되는데 그때마다 이러한 방법으로 Preview를 사용할 수 있다면 화면 개발을 하는데 큰 도움이 될 것 같습니다.