I've noticed that SwiftData's @Relationship seems to potentially cause application crashes.
The crash error is shown in the image.
Since this crash appears to be random and I cannot reproduce it under specific circumstances, I can only temporarily highlight that this issue seems to exist.
@Model final class TrainInfo {
@Relationship(deleteRule: .cascade, inverse: \StopStation.trainInfo)
var stations: [StopStation]?
}
@Model final class StopStation {
@Relationship
var trainInfo: TrainInfo?
}
/// some View
var origin: StopStationDisplayable? {
if let train = train as? TrainInfo {
return train.stations?.first(where: { $0.isOrigin }) ?? train.stations?.first(where: { $0.isStarting })
}
return nil
}
// Some other function or property
func someFunction() {
if let origin, let destination {
// Function implementation
}
}
SwiftData
RSS for tagSwiftData is an all-new framework for managing data within your apps. Models are described using regular Swift code, without the need for custom editors.
Posts under SwiftData tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
If use a SortDescriptor for a model and sort by some attribute from a relationship, in DEBUG mode it all works fine and sorts. However, in release mode, it is an instant crash.
SortDescriptor(.name, order: .reverse) ---- works
SortDescriptor(.assignedUser?.name, order: .reverse) ---- works in debug but crash in release.
What is the issue here, is it that SwiftData just incompetent to do this?
Setup
I am running a versionedSchema for my SwiftData model and attempting a migration. The new version contains a new attribute, with a type of a new custom enum defined in the @Model class, a default value, and a private(set). Migration was completed with a migrationPlan with nil values for willMigrate and didMigrate.
Example - Previous Version
@Model
class MyNumber {
var num: Int
init() {
// Init Code
}
}
Example - Newest Version
@Model
class MyNumber {
var num: Int
private(set) var rounding: RoundAmount = MyNumber.RoundAmount.thirtyMinute
init() {
// Init Code
}
enum RoundAmount {
case fiveMinute, tenMinute, thirtyMinute
}
}
Issue
Running this code, I get a swiftData error for “SwiftData/ModelCoders.swift:1585: nil value passed for a non-optional keyPath, /MyNumber.rounding”
I assume this means a failure of the swiftData lightweight migration? I have reverted the version, removed private(set) and re-tried the migration with no success.
Using the versionedSchema with migrationPlans, are lightweight migrations possible? Could this be an issue with the use of a custom enum? Other changes in my actual project migrated successfully so I’m lost on why I’m having this issue.
Hi there, I got two models here:
Two Models, with Many-To-Many Relationship
@Model
final class PresetParams: Identifiable {
@Attribute(.unique) var id: UUID = UUID()
var positionX: Float = 0.0
var positionY: Float = 0.0
var positionZ: Float = 0.0
var volume: Float = 1.0
@Relationship(deleteRule: .nullify, inverse: \Preset.presetAudioParams)
var preset = [Preset]()
init(position: SIMD3<Float>, volume: Float) {
self.positionX = position.x
self.positionY = position.y
self.positionZ = position.z
self.volume = volume
self.preset = []
}
var position: SIMD3<Float> {
get {
return SIMD3<Float>(x: positionX, y: positionY, z: positionZ)
}
set {
positionX = newValue.x
positionY = newValue.y
positionZ = newValue.z
}
}
}
@Model
final class Preset: Identifiable {
@Attribute(.unique) var id: UUID = UUID()
var presetName: String
var presetDesc: String?
var presetAudioParams = [PresetParams]() // Many-To-Many Relationship.
init(presetName: String, presetDesc: String? = nil) {
self.presetName = presetName
self.presetDesc = presetDesc
self.presetAudioParams = []
}
}
To be honest, I don't fully understand how the @Relationship thing works properly in a Many-To-Many relationship situation. Some tutorials suggest that it's required on the "One" side of an One-To-Many Relationship, while the "Many" side doesn't need it.
And then there is an ObservableObject called "ModelActors" to manage all ModelActors, ModelContainer, etc.
ModelActors, ModelContainer...
class ModelActors: ObservableObject {
static let shared: ModelActors = ModelActors()
let sharedModelContainer: ModelContainer
private init() {
var schema = Schema([
// ...
Preset.self,
PresetParams.self,
// ...
])
do {
sharedModelContainer = try ModelContainer(for: schema, migrationPlan: MigrationPlan.self)
} catch {
fatalError("Could not create ModelContainer: \(error.localizedDescription)")
}
}
}
And there is a migrationPlan:
MigrationPlan
// MARK: V102
// typealias ...
// MARK: V101
typealias Preset = AppSchemaV101.Preset
typealias PresetParams = AppSchemaV101.PresetParams
// MARK: V100
// typealias ...
enum MigrationPlan: SchemaMigrationPlan {
static var schemas: [VersionedSchema.Type] {
[
AppSchemaV100.self,
AppSchemaV101.self,
AppSchemaV102.self,
]
}
static var stages: [MigrationStage] {
[AppMigrateV100toV101, AppMigrateV101toV102]
}
static let AppMigrateV100toV101 = MigrationStage.lightweight(fromVersion: AppSchemaV100.self, toVersion: AppSchemaV101.self)
static let AppMigrateV101toV102 = MigrationStage.lightweight(fromVersion: AppSchemaV101.self, toVersion: AppSchemaV102.self)
}
// MARK: Here is the AppSchemaV101
enum AppSchemaV101: VersionedSchema {
static var versionIdentifier: Schema.Version = Schema.Version(1, 0, 1)
static var models: [any PersistentModel.Type] {
return [ // ...
Preset.self,
PresetParams.self
]
}
}
Fails on iOS 18.3.x: "Failed to fulfill link PendingRelationshipLink"
So I expected the SwiftData subsystem to work correctly with version control. A good news is that on iOS 18.1 it does work. But it fails on iOS 18.3.x with a fatal Error:
"SwiftData/SchemaCoreData.swift:581: Fatal error: Failed to fulfill link PendingRelationshipLink(relationshipDescription: (<NSRelationshipDescription: 0x30377fe80>), name preset, isOptional 0, isTransient 0, entity PresetParams, renamingIdentifier preset, validation predicates (), warnings (), versionHashModifier (null)userInfo {}, destination entity Preset, inverseRelationship (null), minCount 0, maxCount 0, isOrdered 0, deleteRule 1, destinationEntityName: "Preset", inverseRelationshipName: Optional("presetAudioParams")), couldn't find inverse relationship 'Preset.presetAudioParams' in model"
Fails on iOS 17.5: Another Error
I tested it on iOS 17.5 and found another issue: Accessing or mutating the "PresetAudioParams" property causes the SwiftData Macro Codes to crash, affecting both Getter and Setter. It fails with an error:
"EXC_BREAKPOINT (code=1, subcode=0x1cc1698ec)"
Tweaking the @Relationship marker and ModelContainer settings didn't fix the problem.
Hi,
I am creating (or trying to) my first app using SwiftData - and I have questions :-)
The main question I can't get my head wrapped around is the following:
Let's say I have the sample below...
@Model
class Person {
@Relationship(inverse:\Hat.owner) var hat:Hat
}
@Model
class Hat {
var owner:Person?
}
It looks like I am creating a strong reference cycle between the person and the hat objects? And in fact I am seeing these kinds of reference cycles when I look at the memory debugger.
Many code samples I have seen so far use this type of relationship declaration...
And I am wondering: Am I missing something?
Admittedly I don't find many discussions about memory leaks caused by SwiftData despite the syntax being used in many examples?
So what is the situation? Did Apple just miss to explain that the inverse: declaration causes memory leaks or is there some kind of magic that I should understand?
I attempted to create a SortDescriptor using a method in enum to sort various different models in SwiftUI lists.
But it causes crashes in Xcodes previews but not in the simulator, and I don't know why.
Maybe someone could suggest changes.
extension Item:ListSorting {} //List sorting is a protocol given to various Models
enum ListSortingStyle<T>:String,CaseIterable where T:ListSorting {
case alphabetical = "A…Z"
case alphabeticalReverse = "Z…A"
case createDate = "Newest"
case createDateReverse = "Oldest"
case editDate = "Latest Edit"
case editDateReverse = "Oldest Edit"
/// Returns a SortDescriptor matching the enumeration
func sortDescriptor() -> SortDescriptor<T> {
switch self {
case .alphabetical:
SortDescriptor<T>(\.name, comparator: .localized, order: .forward)
case .alphabeticalReverse:
SortDescriptor<T>(\.name, comparator: .localized, order: .reverse)
case .createDate:
SortDescriptor<T>(\.creationDate, order: .forward)
case .createDateReverse:
SortDescriptor<T>(\.creationDate, order: .reverse)
case .editDate:
SortDescriptor<T>(\.editDate, order: .forward)
case .editDateReverse:
SortDescriptor<T>(\.editDate, order: .reverse)
}
}
}
Which is used in
struct ItemsList: View {
@Environment(\.modelContext) private var modelContext
@Query private var items:[Item] = []
init(sortStyle:ListSortingStyle<Item> = .alphabetical) {
let sortDescriptor = SortDescriptor<Item>(\.name, comparator: .localized, order: .forward) //(1) This works in preview & simulator
//OR
let sortDescriptor2 = sortStyle.sortDescriptor() //(2) This crashes in a preview when used in a fetch not in the iOS simulator
print(sortDescriptor,sortDescriptor2)
let descriptor = FetchDescriptor<Item>(sortBy:[sortDescriptor2])
self._items = Query(descriptor)
}
var body: some View {
...
}
}
As far as I can see both methods create a SortDiscriptor. If I print the sortDescriptor variable in they look almost identical:
//1
SortDescriptor<Item>(
order: Foundation.SortOrder.forward,
keyString: nil,
comparison: Foundation.SortDescriptor<MyApp.Item>.AllowedComparison.comparableString(
(extension in Foundation):Swift.String.StandardComparator(options: __C.NSStringCompareOptions(rawValue: 0),
isLocalized: true,
order: Foundation.SortOrder.forward),
\Item. <computed 0x0000000340213b18 (String)>)
)
//2
SortDescriptor<Item>(
order: Foundation.SortOrder.forward,
keyString: nil,
comparison: Foundation.SortDescriptor<MyApp.Item>.AllowedComparison.comparableString(
(extension in Foundation):Swift.String.StandardComparator(options: __C.NSStringCompareOptions(rawValue: 0),
isLocalized: true,
order: Foundation.SortOrder.forward),
\Item.<computed 0x0000000340022174 (String)>)
)
But the one created with the generic method on the enum crashes with the error message:
CrashReportError: Fatal Error in DataUtilities.swift
MyApp crashed due to fatalError in DataUtilities.swift at line 64.
Couldn't find \Item.<computed 0x0000000340022174 (String)> on Item with fields [SwiftData.Schema.PropertyMetadata ...
How do I filter data using @Query with a Set of DateComponents? I successfully saved multiple dates using a MultiDatePicker in AddView.swift. In ListView.swift, I want to retrieve all records for the current or today’s date.
There are hundreds of examples using @Query with strings and dates, but I haven’t found an example of @Query using a Set of DateComponents
Nothing will compile and after hundreds and hundreds of attempts, my hair is turning gray.
Please, please, please help me.
For example, if the current date is Tuesday, March 4 205, then I want to retrieve both records. Since both records contain Tuesday, March 4, then retrieve both records. Sorting works fine because the order by clause uses period which is a Double.
Unfortunately, my syntax is incorrect and I don’t know the correct predicate syntax for @Query and a Set of DateComponents.
Class Planner.swift file
import SwiftUI
import SwiftData
@Model
class Planner {
//var id: UUID = UUID()
var grade: Double = 4.0
var kumi: Double = 4.0
var period: Double = 1.0
var dates: Set<DateComponents> = []
init(
grade: Double = 4.0, kumi: Double = 4.0, period: Double = 1.0, dates: Set<DateComponents> = []
)
{
self.grade = grade
self.kumi = kumi
self.period = period
self.dates = dates
}
}
@Query Model snippet of code does not work
The compile error is to use a Set of DateComponents, not just DateComponents.
@Query(filter: #Predicate<Planner> { $0.dates = DateComponents(calendar: Calendar.current, year: 2025, month: 3, day: 4)},
sort: [SortDescriptor(\Planner.period)])
var planner: [Planner]
ListView.swift image
EditView.swift for record #1
DB Browser for SQLlite: record #1 (March 6, 2025 and March 4, 2025)
[{"isLeapMonth":false,"year":2025,"day":6,"month":3,"calendar":{"identifier":"gregorian","minimumDaysInFirstWeek":1,"current":1,"locale":{"identifier":"en_JP","current":1},"firstWeekday":1,"timeZone":{"identifier":"Asia\/Tokyo"}},"era":1},{"month":3,"year":2025,"day":4,"isLeapMonth":false,"era":1,"calendar":{"locale":{"identifier":"en_JP","current":1},"timeZone":{"identifier":"Asia\/Tokyo"},"current":1,"identifier":"gregorian","firstWeekday":1,"minimumDaysInFirstWeek":1}}]
EditView.swift for record #2
DB Browser for SQLlite: record #2 (March 3, 2025 and March 4, 2025)
[{"calendar":{"minimumDaysInFirstWeek":1,"locale":{"current":1,"identifier":"en_JP"},"timeZone":{"identifier":"Asia\/Tokyo"},"firstWeekday":1,"current":1,"identifier":"gregorian"},"month":3,"day":3,"isLeapMonth":false,"year":2025,"era":1},{"year":2025,"month":3,"era":1,"day":4,"isLeapMonth":false,"calendar":{"identifier":"gregorian","current":1,"firstWeekday":1,"minimumDaysInFirstWeek":1,"timeZone":{"identifier":"Asia\/Tokyo"},"locale":{"current":1,"identifier":"en_JP"}}}]
Any help is greatly appreciated.
I'm trying to find a way to create and use a test cloudkit container in my swiftdata-backed app.
I want to test pre-filling the model container with localized content at first run.
To do this I created a test cloudkit container, and assigned it to my debug build profile in settings and capabilities.
I then conditionally reference the test container in my apps cloudkit manager, i.e.:
private let db: CKDatabase
init() {
#if DEBUG
let container = CKContainer(identifier: "iCloud.com.team-name.myappname.testing-de") // Test CloudKit container
#else
let container = CKContainer(identifier: "iCloud.com.team-name.myappname") // Production CloudKit container
#endif
self.db = container.privateCloudDatabase
}
But when I run my app in debug, content is still created in the primary/production container.
Am I missing something? Or is there a better, or documented, way to test cloudkit more robustly?
For a CRM application, I want users to be able to switch between accounts and have their saved contacts stored locally. Whenever a user logs in, the app should fetch data from their specific database location.
What’s the best practice to achieve this?
Should I create a separate database for each user?
Should I store all the data in one database and filter it by user?
Or is there a better approach I should consider?
Is there a way to move user data from UserDefaults to SwiftData when the app is in production so that people don’t lose their data. Currently my audio journals in my journal app has everything in the UserDefaults. Now this is bad for obvious reasons but I was thinking if there was a way. It’s only been 1 week since published and I have already had17 people download it.
I want to get to a point where I can use a small view with a query for my SwiftData model like this:
@Query
private var currentTrainingCycle: [TrainingCycle]
init(/*currentDate: Date*/) {
_currentTrainingCycle = Query(filter: #Predicate<TrainingCycle> {
$0.numberOfDays > 0
// $0.startDate < currentDate && currentDate < $0.endDate
}, sort: \.startDate)
}
The commented code is where I want to go. In this instance, it'd be created as a lazy var in a viewModel to have it stable (and not constantly re-creating the view). Since it was not working, I thought I could check the same view with a query that does not require any dynamic input. In this case, the numberOfDays never changes after instantiation.
But still, each time the app tries to create this view, the app becomes unresponsive, the CPU usage goes at 196%, memory goes way high and the device heats up quickly.
Am I holding it wrong? How can I have a dynamic predicate on a View in SwiftUI with SwiftData?
Using SwiftData and this is the simplest example I could boil down:
@Model
final class Item {
var timestamp: Date
var tag: Tag?
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class Tag {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
Notice Tag has no reference to Item.
So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors:
SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation)
I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item references to that tag when a Tag is deleted.
But, the damage is already done. How can I iterate through all Items that referenced a deleted tag and set them to nil or to a placeholder Tag? Or how can I catch that error and fix it when it comes up?
The crash doesn't occur when loading an Item, only when accessing item.tag?.timestamp, in fact, item.tag?.id is still ok and doesn't crash since it doesn't have to load the backing data.
I've tried things like just looping through all items and setting tag to nil, but saving the model context fails because somewhere in there it still tries to validate the old value.
Thanks!
Hello, I have a Task model in my application which has an optional many to many relationship to a User model.
task.assignedUsers
user.tasks
I am looking to construct a SwiftData predicate to fetch tasks which either have no assigned users or assigned users does not contain specific user.
Here is a partially working predicate I have now:
static func assignedToOthersPredicate() -> Predicate<Task> {
let currentUserGUID = User.currentUserGUID
return #Predicate<Task> { task in
task.assignedUsers.flatMap { users in
users.contains(where: { $0.guid != currentUserGUID })
} == true
}
}
This only returns tasks assigned to others, but not those which have no assigned users.
If combine it with this:
static func notAssignedPredicate() -> Predicate<Task> {
return #Predicate<Task> { task in
task.assignedUsers == nil
}
}
Then I get a run time crash: "to-many key not allowed here"
What is the proper way to do this?
Thanks.
I have a Package.swift file that builds and runs from Xcode 15.2 without issue but fails to compile when built from the command line ("swift build"). The swift version is 6.0.3. I'm at wits end trying to diagnose this and would welcome any thoughts.
The error in question is
error: external macro implementation type 'SwiftDataMacros.PersistentModelMacro' could not be found for macro 'Model()'; plugin for module 'SwiftDataMacros' not found
The code associated with the module is very vanilla.
import Foundation
import SwiftData
@Model
public final class MyObject {
@Attribute(.unique) public var id:Int64
public var vertexID:Int64
public var updatedAt:Date
public var codeUSRA:Int32
init(id:Int64, vertexID:Int64, updatedAt:Date, codeUSRA:Int32) {
self.id = id
self.vertexID = vertexID
self.updatedAt = updatedAt
self.codeUSRA = codeUSRA
}
public static func create(id:Int64, vertexID:Int64, updatedAt:Date, codeUSRA:Int32) -> MyObject {
MyObject(id: id, vertexID: vertexID, updatedAt: updatedAt, codeUSRA: codeUSRA)
}
}
Thank you.
After copying and inserting instances I am getting strange duplicate values in arrays before saving.
My models:
@Model
class Car: Identifiable {
@Attribute(.unique)
var name: String
var carData: CarData
func copy() -> Car {
Car(
name: "temporaryNewName",
carData: carData
)
}
}
@Model
class CarData: Identifiable {
var id: UUID = UUID()
var featuresA: [Feature]
var featuresB: [Feature]
func copy() -> CarData {
CarData(
id: UUID(),
featuresA: featuresA,
featuresB: featuresB
)
}
}
@Model
class Feature: Identifiable {
@Attribute(.unique)
var id: Int
@Attribute(.unique)
var name: String
@Relationship(
deleteRule:.cascade,
inverse: \CarData.featuresA
)
private(set) var carDatasA: [CarData]?
@Relationship(
deleteRule:.cascade,
inverse: \CarData.featuresB
)
private(set) var carDatasB: [CarData]?
}
The Car instances are created and saved to SwiftData, after that in code:
var fetchDescriptor = FetchDescriptor<Car>(
predicate: #Predicate<Car> {
car in
car.name == name
}
)
let cars = try! modelContext.fetch(
fetchDescriptor
)
let car = cars.first!
print("car featuresA:", car.featuresA.map{$0.name}) //prints ["green"] - expected
let newCar = car.copy()
newCar.name = "Another car"
newcar.carData = car.carData.copy()
print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - expected
modelContext.insert(newCar)
print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green", "green"] - UNEXPECTED!
/*some code planned here modifying newCar.featuresA, but they are wrong here causing issues,
for example finding first expected green value and removing it will still keep the unexpected duplicate
(unless iterating over all arrays to delete all unexpected duplicates - not optimal and sloooooow).*/
try! modelContext.save()
print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - self-auto-healed???
Tested on iOS 18.2 simulator and iOS 18.3.1 device. Minimum deployment target: iOS 17.4
The business logic is that new instances need to be created by copying and modifying previously created ones, but I would like to avoid saving before all instances are created, because saving after creating each instance separately takes too much time overall. (In real life scenario there are more than 10K objects with much more properties, updating just ~10 instances with saving takes around 1 minute on iPhone 16 Pro.)
Is this a bug, or how can I modify the code (without workarounds like deleting duplicate values) to not get duplicate values between insert() and save()?
I have a SwiftData application that is using CloudKit. If user is on new device. How can I check and fetch data, instead of just waiting for it happen on its own randomly?
For example, I have onboarding which I do not want user to go through again if they already have an active installation.
Seems like SwiftData is severely limited in pretty much every way, specially any useful CloudKit debugging or control functionality.
I have not had any successful Schema Migration with CloudKit so far so I'm trying to do with with just very basic attributes, with multiple Versioned Schemas
This is the code in my App Main
var sharedModelContainer: ModelContainer = {
let schema = Schema(versionedSchema: AppSchemaV4.self)
do {
return try ModelContainer(
for: schema,
migrationPlan: AppMigrationPlan.self,
configurations: ModelConfiguration(cloudKitDatabase: .automatic))
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ItemListView()
}
.modelContainer(sharedModelContainer)
}
And this is the code for my MigrationPlan and VersionedSchemas.
typealias Item = AppSchemaV4.Item3
enum AppMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[AppSchemaV1.self, AppSchemaV2.self, AppSchemaV3.self, AppSchemaV4.self]
}
static var stages: [MigrationStage] {
[migrateV1toV2, migrateV2toV3, migrateV3toV4]
}
static let migrateV1toV2 = MigrationStage.lightweight(
fromVersion: AppSchemaV1.self,
toVersion: AppSchemaV2.self
)
static let migrateV2toV3 = MigrationStage.lightweight(
fromVersion: AppSchemaV2.self,
toVersion: AppSchemaV3.self
)
static let migrateV3toV4 = MigrationStage.custom(
fromVersion: AppSchemaV3.self,
toVersion: AppSchemaV4.self,
willMigrate: nil,
didMigrate: { context in
// Fetch all Item1 instances
let item1Descriptor = FetchDescriptor<AppSchemaV3.Item1>()
let items1 = try context.fetch(item1Descriptor)
// Fetch all Item2 instances
let item2Descriptor = FetchDescriptor<AppSchemaV3.Item2>()
let items2 = try context.fetch(item2Descriptor)
// Convert Item1 to Item3
for item in items1 {
let newItem = AppSchemaV4.Item3(name: item.name, text: "Migrated from Item1 on \(item.date)")
context.insert(newItem)
}
// Convert Item2 to Item3
for item in items2 {
let newItem = AppSchemaV4.Item3(name: item.name, text: "Migrated from Item2 with value \(item.value)")
context.insert(newItem)
}
try? context.save()
}
)
}
enum AppSchemaV1: VersionedSchema {
static var versionIdentifier: Schema.Version = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Item1.self]
}
@Model class Item1 {
var name: String = ""
init(name: String) {
self.name = name
}
}
}
enum AppSchemaV2: VersionedSchema {
static var versionIdentifier: Schema.Version = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Item1.self]
}
@Model class Item1 {
var name: String = ""
var date: Date = Date()
init(name: String) {
self.name = name
self.date = Date()
}
}
}
enum AppSchemaV3: VersionedSchema {
static var versionIdentifier: Schema.Version = Schema.Version(3, 0, 0)
static var models: [any PersistentModel.Type] {
[Item1.self, Item2.self]
}
@Model class Item1 {
var name: String = ""
var date: Date = Date()
init(name: String) {
self.name = name
self.date = Date()
}
}
@Model class Item2 {
var name: String = ""
var value: Int = 0
init(name: String, value: Int) {
self.name = name
self.value = value
}
}
}
enum AppSchemaV4: VersionedSchema {
static var versionIdentifier: Schema.Version = Schema.Version(4, 0, 0)
static var models: [any PersistentModel.Type] {
[Item1.self, Item2.self, Item3.self]
}
@Model class Item1 {
var name: String = ""
var date: Date = Date()
init(name: String) {
self.name = name
self.date = Date()
}
}
@Model class Item2 {
var name: String = ""
var value: Int = 0
init(name: String, value: Int) {
self.name = name
self.value = value
}
}
@Model class Item3 {
var name: String = ""
var text: String = ""
init(name: String, text: String) {
self.name = name
self.text = text
}
}
}
My experiment was:
To create Items for every version of the schema
Updating the typealias along the way to reflect the latest Item version.
Updating the Schema in my ModelContainer to reflect the latest Schema Version.
By AppSchemaV4, I have expected all my Items to be displayed/migrated to Item3, but it does not seem to be the case.
I can only see newly created Item3 records.
My question is, is there something wrong with how I'm doing the migrations? or are migrations not really working with CloudKit right now?
Hi,
Before the iOS 17.2 update the saving behavior of SwiftData was very straightforward, by default it saves to persistence storage and can be configured to save in memory only. Now it saves to memory by default and to make it save to persistence storage we need to use modelContext.Save(). But if we don't quit the App the changes will be saved after a while to persistence storage even without running modelContext.Save() ! How confusing can that be for both developer and the user ! Am I missing something here ?
--
Kind Regards
In my app, I've been using ModelActors in SwiftData, and using actors with a custom executor in Core Data to create concurrency safe services.
I have multiple actor services that relate to different data model components or features, each that have their own internally managed state (DocumentService, ImportService, etc).
The problem I've ran into, is that I need to be able to use multiple of these services within another service, and those services need to share the same context. Swift 6 doesn't allow passing contexts across actors.
The specific problem I have is that I need a master service that makes multiple unrelated changes without saving them to the main context until approved by the user.
I've tried to find a solution in SwiftData and Core Data, but both have the same problem which is contexts are not sendable. Read the comments in the code to see the issue:
/// This actor does multiple things without saving, until committed in SwiftData.
@ModelActor
actor DatabaseHelper {
func commitChange() throws {
try modelContext.save()
}
func makeChanges() async throws {
// Do unrelated expensive tasks on the child context...
// Next, use our item service
let service = ItemService(modelContainer: SwiftDataStack.shared.container)
let id = try await service.expensiveBackgroundTask(saveChanges: false)
// Now that we've used the service, we need to access something the service created.
// However, because the service created its own context and it was never saved, we can't access it.
let itemFromService = context.fetch(id) // fails
// We need to be able to access changes made from the service within this service,
/// so instead I tried to create the service by passing the current service context, however that results in:
// ERROR: Sending 'self.modelContext' risks causing data races
let serviceFromContext = ItemService(context: modelContext)
// Swift Data doesn't let you create child contexts, so the same context must be used in order to change data without saving.
}
}
@ModelActor
actor ItemService {
init(context: ModelContext) {
modelContainer = SwiftDataStack.shared.container
modelExecutor = DefaultSerialModelExecutor(modelContext: context)
}
func expensiveBackgroundTask(saveChanges: Bool = true) async throws -> PersistentIdentifier? {
// Do something expensive...
return nil
}
}
Core Data has the same problem:
/// This actor does multiple things without saving, until committed in Core Data.
actor CoreDataHelper {
let parentContext: NSManagedObjectContext
let context: NSManagedObjectContext
/// In Core Data, I can create a child context from a background context.
/// This lets you modify the context and save it without updating the main context.
init(progress: Progress = Progress()) {
parentContext = CoreDataStack.shared.newBackgroundContext()
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
self.context = childContext
}
/// To commit changes, save the parent context pushing them to the main context.
func commitChange() async throws {
// ERROR: Sending 'self.parentContext' risks causing data races
try await parentContext.perform {
try self.parentContext.save()
}
}
func makeChanges() async throws {
// Do unrelated expensive tasks on the child context...
// As with the Swift Data example, I am unable to create a service that uses the current actors context from here.
// ERROR: Sending 'self.context' risks causing data races
let service = ItemService(context: self.context)
}
}
Am I going about this wrong, or is there a solution to fix these errors?
Some services are very large and have their own internal state. So it would be very difficult to merge all of them into a single service. I also am using Core Data, and SwiftData extensively so I need a solution for both.
I seem to have trapped myself into a corner trying to make everything concurrency save, so any help would be appreciated!
I have a model with a FamilyActivitySelection, currently i'm using a codable struct to store it with UserDefaults, but would prefer strongly to transition to Swift Data