SwiftData 的全部使用流程
SwiftData 是 Apple 在 WWDC 2023 中推出的新框架,它简化了 Swift 应用程序中的数据持久化。下面我将介绍 SwiftData 的完整使用流程:
1. 创建模型
首先,需要定义数据模型。在 SwiftData 中,模型是通过遵循 Model 协议的类来定义的:
import SwiftData
@Model
class Trip {
var name: String
var destination: String
var startDate: Date
var endDate: Date
var notes: String?
init(name: String, destination: String, startDate: Date, endDate: Date, notes: String? = nil) {
self.name = name
self.destination = destination
self.startDate = startDate
self.endDate = endDate
self.notes = notes
}
}
2. 设置 ModelContainer
在应用中使用 SwiftData 需要设置 ModelContainer:
import SwiftUI
import SwiftData
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Trip.self)
}
}
如果有多个模型,可以这样设置:
...
3. 在视图中使用 ModelContext
在视图中,可以通过 @Environment 获取 ModelContext:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var trips: [Trip]
var body: some View {
NavigationView {
List {
ForEach(trips) { trip in
NavigationLink {
TripDetailView(trip: trip)
} label: {
Text(trip.name)
}
}
.onDelete(perform: deleteTrips)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
addTrip()
} label: {
Label("添加行程", systemImage: "plus")
}
}
}
}
}
private func addTrip() {
let newTrip = Trip(
name: "新行程",
destination: "未知目的地",
startDate: Date(),
endDate: Date().addingTimeInterval(86400 * 7)
)
modelContext.insert(newTrip)
}
private func deleteTrips(offsets: IndexSet) {
for index in offsets {
modelContext.delete(trips[index])
}
}
}