일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- @NameSpace
- Custom URL Scheme
- SwiftData
- Universal Link
- ScrollViewProxy
- @ObservedObject
- Combine vs Async/Await
- async/await
- async
- fileprivate
- The Composable Architecture
- Dynamic Dispatch
- combine
- MVVM
- await
- wwdc23
- Static Dispatch
- Concurrency Programming
- @StateObject
- ScrollViewReader
- ios
- SFSafariView
- AnyCancellable
- SwiftUI
- 이것이나의다정입니다
- matchedGeometryEffect
- architecture
- App Thinning
- @main
- swift
- Today
- Total
홍로그
WWDC23 SwiftData 본문
📖SwiftData란?
SwiftData는 Swift 언어를 기반으로 한 강력한 데이터 모델링 및 관리 프레임워크입니다. 이 프레임워크는 현대적인 Swift 앱을 개발하는 데 사용되며, SwiftUI와 완벽하게 통합되어 앱의 데이터 모델을 효과적으로 관리할 수 있습니다. 또한 CloudKit와 같은 다른 플랫폼 기능과도 원활하게 작동합니다.
SwiftData는 외부 파일 형식 없이 코드에만 집중하며, Swift의 새로운 매크로 시스템을 활용하여 매끄러운 API 경험을 제공합니다. SwiftData는 데이터 모델을 정의하기 위해 새로운 @Model 매크로를 도입하였습니다. SwiftData의 스키마는 일반적인 Swift 코드로 작성되지만, 필요한 경우 속성에 추가 메타데이터를 주석으로 추가할 수 있습니다.
SwiftData의 핵심 개념은 모델 객체를 중심으로 하며, SwiftUI와 자연스럽게 통합되어 동작합니다. SwiftData는 @Model을 사용하여 클래스에 적용함으로써 모델 객체에 강력한 기능을 제공합니다. SwiftData는 다양한 유형의 속성을 손쉽게 처리할 수 있으며, 기본적인 값 유형인 문자열, 정수, 부동 소수점을 포함하여 구조체, 열거형, Codable 타입 및 컬렉션과 같은 복잡한 값 유형도 처리할 수 있습니다.
import SwiftData
@Model
class Trip {
var name: String
var destination: String
var endDate: Date
var startDate: Date
var bucketList: [BucketListItem]? = []
var livingAccommodation: LivingAccommodation?
}
SwiftData는 관계를 나타내기 위해 모델 간의 참조 타입을 사용합니다. 관계와 모델 타입의 컬렉션을 사용하여 모델 타입 간에 링크를 생성할 수 있습니다. 속성에 메타데이터를 사용하여 SwiftData가 스키마를 구축하는 방법을 조정할 수 있습니다. 예를 들어, @Attribute를 사용하여 고유성 제약 조건을 추가하거나, @Relationship을 사용하여 반대 관계의 선택과 삭제 전파 규칙을 지정할 수 있습니다. 또한 Transient 매크로를 사용하여 특정 속성을 제외할 수도 있습니다.
@Model
class Trip {
@Attribute(.unique) var name: String
var destination: String
var endDate: Date
var startDate: Date
@Relationship(.cascade) var bucketList: [BucketListItem]? = []
var livingAccommodation: LivingAccommodation?
}
SwiftData를 사용하면 데이터를 가져오고 수정하는 방법을 배울 수 있으며, SwiftData와 원활하게 작동하는 다른 플랫폼 프레임워크에 대한 개요도 제공됩니다. 데이터 검색을 위해 예측 및 fetch 디스크립터를 활용할 수 있으며, Swift의 네이티브 정렬 디스크립터도 사용할 수 있습니다.
let descriptor = FetchDescriptor<Trip>(predicate: tripPredicate)
let trips = try context.fetch(descriptor)
let descriptor = FetchDescriptor<Trip>(
sortBy: SortDescriptor(\Trip.name),
predicate: tripPredicate
)
let trips = try context.fetch(descriptor)
또한, SwiftData를 사용하여 모델 컨테이너와 모델 콘텍스트를 구성하고 데이터를 조작하는 방법에 대해서도 설명되어 있습니다. 모델 컨테이너는 모델 타입의 영구적인 백엔드를 제공하며, 모델 콘텍스트는 모델에 대한 작업을 수행하는 데 필요한 핵심 개체입니다. 모델 콘텍스트를 통해 데이터의 변경 사항을 추적하고 저장할 수 있으며, SwiftUI의 view와 scene 수정자를 사용하여 컨테이너를 설정하고 환경에서 자동으로 활성화할 수 있습니다.
// Initialize with only a schema
let container = try ModelContainer([Trip.self, LivingAccommodation.self])
// Initialize with configurations
let container = try ModelContainer(
for: [Trip.self, LivingAccommodation.self],
configurations: ModelConfiguration(url: URL("path"))
)
import SwiftUI
@main
struct TripsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(
for: [Trip.self, LivingAccommodation.self]
)
}
}
SwiftData는 데이터의 생성, 삭제, 변경을 쉽게 할 수 있도록 지원하며, 모델 콘텍스트를 사용하여 이러한 작업을 수행할 수 있습니다. 또한, SwiftUI의 @Query 속성 래퍼를 사용하여 데이터베이스에 저장된 내용을 쉽게 로드하고 필터링할 수 있습니다. SwiftUI와 SwiftData는 함께 사용하여 매력적이고 강력한 앱을 구축하는 데 도움을 줍니다.
var myTrip = Trip(name: "Birthday Trip", destination: "New York")
// Insert a new trip
context.insert(myTrip)
// Delete an existing trip
context.delete(myTrip)
// Manually save changes to the context
try context.save()
import SwiftUI
struct ContentView: View {
@Query(sort: \.startDate, order: .reverse) var trips: [Trip]
@Environment(\.modelContext) var modelContext
var body: some View {
NavigationStack() {
List {
ForEach(trips) { trip in
// ...
}
}
}
}
}
SwiftData는 Swift의 기능을 완벽하게 활용하며, 데이터 관리를 위한 강력한 도구입니다. @Model을 사용하여 스키마를 설정하고, 모델 컨테이너를 통해 지속성, 롤백, iCloud 동기화, 위젯 개발 등을 간편하게 구성할 수 있습니다. SwiftUI와의 원활한 통합을 통해 바로 앱에 SwiftData를 구축할 수 있습니다.
참고
https://developer.apple.com/documentation/SwiftData
SwiftData | Apple Developer Documentation
Write your model code declaratively to add managed persistence and automatic iCloud sync.
developer.apple.com
https://developer.apple.com/videos/play/wwdc2023/10187/
Meet SwiftData - WWDC23 - Videos - Apple Developer
SwiftData is a powerful and expressive persistence framework built for Swift. We'll show you how you can model your data directly from...
developer.apple.com
'iOS' 카테고리의 다른 글
DeepLink (0) | 2023.06.20 |
---|---|
Combine AnyCancellable (0) | 2023.06.19 |
SwiftUI @NameSpace (0) | 2023.06.13 |
SwiftUI ScrollView, ScrollViewReader, ScrollViewProxy (0) | 2023.06.12 |
Swift @main (0) | 2023.06.07 |