2023 Swift
Migrate to SwiftData
Discover how you can start using SwiftData in your apps. We’ll show you how to use Xcode to generate model classes from your existing Core Data object models, use SwiftData alongside your previous implementation, or even completely replace your existing solution. Before watching this session, make sure you check out "Meet SwiftData."
Watch at developer.apple.com ↗Chapters
Code shown on screen · 6 snippets
Creating a ModelContainer in SwiftUI
@main
struct TripsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(
for: [Trip.self, BucketListItem.self, LivingAccommodation.self]
)
}
} Object creation in Core Data
(\.managedObjectContext) private var viewContext
let newTrip = Trip(context: viewContext)
newTrip.name = name
newTrip.destination = destination
newTrip.startDate = startDate
newTrip.endDate = endDate Object creation in SwiftData
(\.modelContext) private var modelContext
let trip = Trip(
name: name,
destination: destination,
startDate: startDate,
endDate: endDate
)
modelContext.insert(object: trip) Fetch with Query in SwiftData
(sort: \.startDate, order: .forward)
var trips: [Trip] Setting store path and enabling persistent history tracking in Core Data
let url = URL(fileURLWithPath: "/path/to/Trips.store")
if let description = container.persistentStoreDescriptions.first {
description.url = url
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
} Ensuring Core Data and SwiftData class names are unique
class CDTrip: NSManagedObject {
// ...
}
final class Trip {
// ...
} Resources
Related sessions
-
13 min -
19 min -
9 min -
9 min -
16 min