Hi guys. Can someone please confirm this bug so I report it? The issue is that SwiftData relationships don't update the views in some specific situations on devices running iOS 18 Beta. One clear example is with CloudKit. I created a small example for testing. The following code creates two @models, one to store bands and another to store their records. The following code works with no issues. (You need to connect to a CloudKit container and test it on two devices)
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var records: [Record]
var body: some View {
NavigationStack {
List(records) { record in
VStack(alignment: .leading) {
Text(record.title)
Text(record.band?.name ?? "Undefined")
}
}
.toolbar {
ToolbarItem {
Button("Add Record") {
let randomNumber = Int.random(in: 1...100)
let newBand = Band(name: "New Band \(randomNumber)", records: nil)
modelContext.insert(newBand)
let newRecord = Record(title: "New Record \(randomNumber)", band: newBand)
modelContext.insert(newRecord)
}
}
}
}
}
}
@Model
final class Record {
var title: String = ""
var band: Band?
init(title: String, band: Band?) {
self.title = title
self.band = band
}
}
@Model
final class Band {
var name: String = ""
var records: [Record]?
init(name: String, records: [Record]?) {
self.name = name
self.records = records
}
}
This view includes a button at the top to add a new record associated with a new band. The data appears on both devices, but if you include more views inside the List, the views on the second device are not updated to show the values of the relationships. For example, if you extract the row to a separate view, the second device shows the relationships as "Undefined". You can try the following code.
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var records: [Record]
var body: some View {
NavigationStack {
List {
ForEach(records) { record in
RecordRow(record: record)
}
}
.toolbar {
ToolbarItem {
Button("Add Record") {
let randomNumber = Int.random(in: 1...100)
let newBand = Band(name: "New Band \(randomNumber)", records: nil)
modelContext.insert(newBand)
let newRecord = Record(title: "New Record \(randomNumber)", band: newBand)
modelContext.insert(newRecord)
}
}
}
}
}
}
struct RecordRow: View {
let record: Record
var body: some View {
VStack(alignment: .leading) {
Text(record.title)
Text(record.band?.name ?? "Undefined")
}
}
}
Here I use a ForEach loop and move the row to a separate view. Now on the second device the relationships are nil, so the row shows the text "Undefined" instead of the name of the band.
I attached an image from my iPad. I inserted all the information on my iPhone. The first three rows were inserted with the first view. But the last two rows were inserted after I extracted the rows to a separate view. Here you can see that the relationships are nil and therefore shown as "Undefined". The views are not updated to show the real value of the relationship.
This example shows the issue with CloudKit, but this also happens locally in some situations. The system doesn't detect updates in relationships and therefore doesn't refresh the views.
Please, let me know if you can reproduce the issue. I'm using Mac Sequoia 15.1, and two devices with iOS 18.0.
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi everyone!
I have an app on the App Store that uses Core Data as its data store. (It's called Count on Me: Tally Counter. Feel free to check it out.) One of the app's core feature is an interactive widget with a simple button. When the button is tapped, it's supposed to update the entity in the store.
My requirement is that the changes are then reflected with minimal latency in the main app and – ideally – also on other devices of the same iCloud user. And vice-versa: When an entity is updated in the app (or on another device where the same iCloud user is logged in), the widget that shows this entity should also refresh to reflect the changes.
I have read multiple articles, downloaded sample projects, searched Stackoverflow and the Apple developer forums, and tried to squeeze a solution out of AI, but couldn't figure out how to make this work reliably.
So I tried to reduce the core problem to a minimal example project. It has two issues that I cannot resolve:
When I update an entity in the app, the widget is immediately updated as intended (due to a call to WidgetCenter's reloadAllTimelines method). However, when I update the same entity from the interactive widget using the same app intent, the changes are not reflected in the main app.
For the widget and the app to use the same local data store, I need to enable App Groups in both targets and set a custom location for the store within the shared app group. So I specify a custom URL for the NSPersistentStoreDescription when setting up the Core Data stack. The moment I do this, iCloud sync breaks.
Issue no. 1 is far more important to me as I haven't officially enabled iCloud sync yet in my real app that's already on the App Store. But it would be wonderful to resolve issue no. 2 as well. Surely, there must be a way to synchronize changes to the source of truth triggered by interactive widget with other devices of the same iCloud user. Otherwise, the feature to talk to the main app and the feature to synchronize with iCloud would be mutually exclusive.
Some other developers I talked to have suggested that the widget should only communicate proposed changes to the main app and once the main app is opened, it processes these changes and writes them to the NSPersistentCloudKitContainer which then synchronizes across devices. This is not an option for me as it would result in a stale state and potential data conflicts with different devices. For example, when a user has the same widget on their iPhone and their iPad, taps a button on the iPhone widget, that change would not be reflected on the iPad widget until the user decides to open the app on the iPhone. At the same time, the user could tap the button multiple times on their iPad widget, resulting in a conflicting state on both devices. Thus, this approach is not a viable solution.
An answer to this question will be greatly appreciated. The whole code including the setup of the Core Data stack is included in the repository reference above. Thank you!
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.
error: the replacement path doesn't exist <- how bad is this error, should i care - is it important?
I get this error, i have my own DIKit, and i want to use swiftdata for showing info from persisten model. It works all over the app, but i get this error with my .sheet.
// JobCreationView.swift
// Features
//
// Created by Jens Vik on 26/03/2025.
//
import SwiftUI
import DesignKit
import DIKit
import PresentationKit
import CoreKit
import DomainKit
import SwiftData
public struct JobCreationView: View {
@Binding var isPresented: Bool
// Inject view model using DIKit's property wrapper
@Injected((any JobCreationViewModelProtocol).self) private var viewModel
// Form state
@Injected(ModelContext.self) private var modelContext
@State private var date = Date()
@State private var isASAP = false
@State private var price = ""
@State private var jobType = "Fiks"
@State private var description = ""
// Available job types
private let jobTypes = ["Fiks", "Fiksit"]
@Query private var userContexts: [UserContextModel]
public init(isPresented: Binding<Bool>) {
self._isPresented = isPresented
print("DEBUG: JobCreationView initialized")
}
public var body: some View {
let city = userContexts.first?.city ?? "Loading..."
NavigationView {
Form {
Section(header: Text("Location")) {
Text(city)
}
Section(header: Text("Details")) {
TextField("Price", text: $price)
.keyboardType(.numberPad)
Picker("Job Type", selection: $jobType) {
ForEach(jobTypes, id: \.self) { type in
Text(type).tag(type)
}
}
.pickerStyle(SegmentedPickerStyle())
TextEditor(text: $description)
.frame(minHeight: 100)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
}
}
.navigationBarTitle("Create Job", displayMode: .inline)
.navigationBarItems(
leading: Button("Cancel") {
isPresented = false
},
trailing: Button("Post") {
// Post functionality will be added later
isPresented = false
}
.disabled( (!isASAP && date < Date()) || price.isEmpty || description.isEmpty)
)
}
}
}
How bad is this macro error?
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
Topic:
App & System Services
SubTopic:
iCloud & Data
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.
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?
I'm looking for guidance how to mitigate this crash. It seems super deep inside Core Data' FRC fetchedObjects management.
In my code, it's initiated by this
viewContext.perform {
[unowned self] in
self.viewContext.mergeChanges(fromContextDidSave: notification)
}
which is directly followed by the stack trace below.
Basically merging data from .NSManagedObjectContextDidSave notification from another NSManagedObjectContext. Nothing special, it works great for years, apart from these rare occurrences.
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Reason: -[__NSCFArray objectAtIndex:]: index (235) beyond bounds (234)
Termination Reason: SIGNAL 6 Abort trap: 6
Triggered by Thread: 0
Last Exception Backtrace:
0 CoreFoundation 0x199e947cc __exceptionPreprocess + 164 (NSException.m:249)
1 libobjc.A.dylib 0x1971672e4 objc_exception_throw + 88 (objc-exception.mm:356)
2 CoreFoundation 0x199fc4258 _NSArrayRaiseBoundException + 368 (NSCFArray.m:22)
3 CoreFoundation 0x199e288a4 -[__NSCFArray objectAtIndex:] + 200 (NSCFArray.m:42)
4 CoreData 0x1a1e17338 -[_PFMutableProxyArray objectAtIndex:] + 40 (_PFArray.m:1860)
5 CoreData 0x1a1e1673c -[NSFetchedResultsController _updateFetchedObjectsWithInsertChange:] + 380 (NSFetchedResultsController.m:1582)
6 CoreData 0x1a1e1426c __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke + 2240 (NSFetchedResultsController.m:2171)
7 CoreData 0x1a1dcdf80 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:4002)
8 CoreData 0x1a1e41a44 -[NSManagedObjectContext performBlockAndWait:] + 216 (NSManagedObjectContext.m:4113)
9 CoreData 0x1a1e41034 -[NSFetchedResultsController _core_managedObjectContextDidChange:] + 124 (NSFetchedResultsController.m:2379)
10 CoreFoundation 0x199e632f4 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 (CFNotificationCenter.c:701)
11 CoreFoundation 0x199e63210 ___CFXRegistrationPost_block_invoke + 88 (CFNotificationCenter.c:194)
12 CoreFoundation 0x199e63158 _CFXRegistrationPost + 436 (CFNotificationCenter.c:222)
13 CoreFoundation 0x199e6170c _CFXNotificationPost + 728 (CFNotificationCenter.c:1248)
14 Foundation 0x198a84ea4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 92 (NSNotification.m:531)
15 CoreData 0x1a1e11650 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1736 (NSManagedObjectContext.m:8098)
16 CoreData 0x1a1e10e0c -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] + 164 (NSManagedObjectContext.m:7631)
17 CoreData 0x1a1e0fad8 -[NSManagedObjectContext _processRecentChanges:] + 100 (NSManagedObjectContext.m:7714)
18 CoreData 0x1a1e3563c -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] + 3436 (NSManagedObjectContext.m:3723)
19 CoreData 0x1a1e34350 __116+[NSManagedObjectContext(_NSCoreDataSPI) _mergeChangesFromRemoteContextSave:intoContexts:withClientQueryGeneration:]_block_invoke_4 + 76 (NSManagedObjectContext.m:9531)
20 CoreData 0x1a1dcdf80 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:4002)
21 CoreData 0x1a1e41a44 -[NSManagedObjectContext performBlockAndWait:] + 216 (NSManagedObjectContext.m:4113)
22 CoreData 0x1a1e39880 +[NSManagedObjectContext _mergeChangesFromRemoteContextSave:intoContexts:withClientQueryGeneration:] + 2372 (NSManagedObjectContext.m:9537)
23 CoreData 0x1a1e344a0 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] + 292 (NSManagedObjectContext.m:0)
Topic:
App & System Services
SubTopic:
iCloud & Data
There's some logic in my app that first checks to see if a specific CloudKit record zone exists. If it doesn't, it creates the zone, and then my application continues on with its work.
The way I've implemented this right now is by catching the zoneNotFound error when I call CKDatabase#recordZone(for:) (docs) and creating the zone when that happens:
do {
try await db.recordZone(for: zoneID)
} catch let ckError as CKError
where [.zoneNotFound, .userDeletedZone].contains(ckError.code)
{
// createZone is a helper function
try await createZone(zoneID: zoneID, context: context)
}
This works great, but every time I do this, an error is logged in CloudKit Console, which creates a lot of noise and makes it harder to see real errors.
Is there a way to do this without explicitly triggering a CloudKit error?
I just found CKDatabase#recordZones(for:) (docs), which seems like it returns an empty array instead of throwing an error if the zone doesn't exist.
Will calling that and looking for a non-empty array work just as well, but without logging lots of errors in the console?
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
}
}
The following complex migration consistently crashes the app with the following error:
SwiftData/PersistentModel.swift:726: Fatal error: What kind of backing data is this? SwiftData._KKMDBackingData<SwiftDataMigration.ItemSchemaV1.ItemList>
My app relies on a complex migration that involves these optional 1 to n relationships. Theoretically I could not assign the relationships in the willMigrate block but afterwards I am not able to tell which list and items belonged together.
Steps to reproduce:
Run project
Change typealias CurrentSchema to ItemSchemaV2 instead of ItemSchemaV1.
Run project again -> App crashes
My setup:
Xcode Version 16.2 (16C5032a)
MacOS Sequoia 15.4
iPhone 12 with 18.3.2 (22D82)
Am I doing something wrong or did I stumble upon a bug? I have a demo Xcode project ready but I could not upload it here so I put the code below.
Thanks for your help
typealias CurrentSchema = ItemSchemaV1
typealias ItemList = CurrentSchema.ItemList
typealias Item = CurrentSchema.Item
@main
struct SwiftDataMigrationApp: App {
var sharedModelContainer: ModelContainer = {
do {
return try ModelContainer(for: ItemList.self, migrationPlan: MigrationPlan.self)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
This is the migration plan
enum MigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ItemSchemaV1.self, ItemSchemaV2.self]
}
static var stages: [MigrationStage] = [
MigrationStage.custom(fromVersion: ItemSchemaV1.self, toVersion: ItemSchemaV2.self, willMigrate: { context in
print("Started migration")
let oldlistItems = try context.fetch(FetchDescriptor<ItemSchemaV1.ItemList>())
for list in oldlistItems {
let items = list.items.map { ItemSchemaV2.Item(timestamp: $0.timestamp)}
let newList = ItemSchemaV2.ItemList(items: items, name: list.name, note: "This is a new property")
context.insert(newList)
context.delete(list)
}
try context.save() // Crash indicated here
print("Finished willMigrate")
}, didMigrate: { context in
print("Did migrate successfully")
})
]
}
The versioned schemas
enum ItemSchemaV1: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var list: ItemSchemaV1.ItemList?
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class ItemList {
@Relationship(deleteRule: .cascade, inverse: \ItemSchemaV1.Item.list)
var items: [Item]
var name: String
init(items: [Item], name: String) {
self.items = items
self.name = name
}
}
}
enum ItemSchemaV2: VersionedSchema {
static var versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var list: ItemSchemaV2.ItemList?
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class ItemList {
@Relationship(deleteRule: .cascade, inverse: \ItemSchemaV2.Item.list)
var items: [Item]
var name: String
var note: String
init(items: [Item], name: String, note: String = "") {
self.items = items
self.name = name
self.note = note
}
}
}
Last the ContentView:
struct ContentView: View {
@Query private var itemLists: [ItemList]
var body: some View {
NavigationSplitView {
List {
ForEach(itemLists) { list in
NavigationLink {
List(list.items) { item in
Text(item.timestamp.formatted(date: .abbreviated, time: .complete))
}
.navigationTitle(list.name)
} label: {
Text(list.name)
}
}
}
.navigationTitle("Crashing migration demo")
.onAppear {
if itemLists.isEmpty {
for index in 0..<10 {
let items = [Item(timestamp: Date.now)]
let listItem = ItemList(items: items, name: "List No. \(index)")
modelContext.insert(listItem)
}
try! modelContext.save()
}
}
} detail: {
Text("Select an item")
}
}
}
I'm developing a SwiftUI app using SwiftData and encountering a persistent issue:
Error Message:
Thread 1: Fatal error: Duplicate keys of type 'Bland' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or that members of such a dictionary were mutated after insertion.
Details:
Occurrence: The error always occurs on the first launch of the app after installation. Specifically, it happens approximately 1 minute after the app starts.
Inconsistent Behavior: Despite no changes to the code or server data, the error occurs inconsistently.
Data Fetching Process:
I fetch data for entities (Bland, CrossZansu, and Trade) from the server using the following process:
Fetch Bland and CrossZansu entities via URLSession.
Insert or update these entities into the SwiftData context.
The fetched data is managed as follows:
func refleshBlandsData() async throws {
if let blandsOnServer = try await DataModel.shared.getBlands() {
await MainActor.run {
blandsOnServer.forEach { blandOnServer in
if let blandOnLocal = blandList.first(where: { $0.code == blandOnServer.code }) {
blandOnLocal.update(serverBland: blandOnServer)
} else {
modelContext.insert(blandOnServer.bland)
}
}
}
}
}
This is a simplified version of my StockListView. The blandList is a @Query property and dynamically retrieves data from SwiftData:
struct StockListView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: \Bland.sname) var blandList: [Bland]
@Query var users: [User]
@State private var isNotLoaded = true
@State private var isLoading = false
@State private var loadingErrorState = ""
var body: some View {
NavigationStack {
List {
ForEach(blandList, id: \.self) { bland in
NavigationLink(value: bland) {
Text(bland.sname)
}
}
}
.navigationTitle("Stock List")
.onAppear {
doIfFirst()
}
}
}
// This function handles data loading when the app launches for the first time
func doIfFirst() {
if isNotLoaded {
loadDataWithAnimationIfNotLoading()
isNotLoaded = false
}
}
// This function ensures data is loaded with an animation and avoids multiple triggers
func loadDataWithAnimationIfNotLoading() {
if !isLoading {
isLoading = true
Task {
do {
try await loadData()
} catch {
// Capture and store any errors during data loading
loadingErrorState = "Data load failed: \(error.localizedDescription)"
}
isLoading = false
}
}
}
// Fetch data from the server and insert it into the SwiftData model context
func loadData() async throws {
if let blandsOnServer = try await DataModel.shared.getBlands() {
for bland in blandsOnServer {
// Avoid inserting duplicate keys by checking for existing items in blandList
if !blandList.contains(where: { $0.code == bland.code }) {
modelContext.insert(bland.bland)
}
}
}
}
}
Entity Definitions:
Here are the main entities involved:
Bland:
@Model
class Bland: Identifiable {
@Attribute(.unique) var code: String
var sname: String
@Relationship(deleteRule: .cascade, inverse: \CrossZansu.bland)
var zansuList: [CrossZansu]
@Relationship(deleteRule: .cascade, inverse: \Trade.bland)
var trades: [Trade]
}
CrossZansu:
@Model
class CrossZansu: Equatable {
@Attribute(.unique) var id: String
var bland: Bland?
}
Trade:
@Model
class Trade {
@Relationship(deleteRule: .nullify)
var user: User?
var bland: Bland
}
User:
class User {
var id: UUID
@Relationship(deleteRule: .cascade, inverse: \Trade.user)
var trades: [Trade]
}
Observations:
Error Context: The error occurs after the data is fetched and inserted into SwiftData. This suggests an issue with Hashable requirements or duplicate keys being inserted unintentionally.
Concurrency Concerns: The fetch and update operations are performed in asynchronous tasks. Could this cause race conditions?
Questions:
Could this issue be related to how @Relationship and @Attribute(.unique) are managed in SwiftData?
What are potential pitfalls with Equatable implementations (e.g., in CrossZansu) when used in SwiftData entities?
Are there any recommended approaches for debugging "Duplicate keys" errors in SwiftData?
Additional Info:
Error Timing: The error occurs only during the app's first launch and consistently within the first minute.
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.
Hello everyone,
I used SwiftData for v1 of an app and am now trying to make changes to the schema for v2. I created the v2 schema that adds a property to one of the models.
I need to populate the new property so I made a custom migration using didMigrate. However that doesn't seem to matter what I do in the migration because creating the ModelContainer throws an error before didMigrate ever gets called.
The error is:
Unresolved error loading container Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Instances of NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore.}
Higher up in the Xcode output I see things like this (in order):
Request 'D25A8CB8-7341-4FA8-B2F8-3DE2D35B5273' was cancelled because the store was removed from the coordinator.
BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered
CloudKit setup failed because it couldn't register a handler for the export activity. There is another instance of this persistent store actively syncing with CloudKit in this process.
How can I know from this output what I am doing incorrectly?
Any idea what I should take a look at or try to do differently?
This is a simple app with three models and nothing fancy. The only change in the schema is to add a property. The new property is declared as optional and has an inverse that is also declared as optional.
Thanks for any insight!
Some of my customer get the following CloudKit error (I cannot reproduce is myself).
Failed to modify some records (CKErrorDomain:2)
userInfo: CKErrorDescription:Failed to modify some records CKPartialErrors:{
"<CKRecordID: ooo; recordName=ooo, zoneID=ooo:__defaultOwner__>"
= "<CKError 0x600003809ce0: \"Limit Exceeded\" (27/2023); server message = \"AssetUploadTokenRetrieveRequest request size exceeds limit\";
op = ooo; uuid = ooo; container ID = \"ooo\">"
This is a CKError.limitExeeded error.
I create 200 or less records in a batch operation. So I am below the 400 limit.
Searching the Internet for "AssetUploadTokenRetrieveRequest request size exceeds limit": 0 results
Can anyone give me a hint?
Since the iOS 18 and Xcode 16, I've been getting some really strange SwiftData errors when passing @Model classes around.
The error I'm seeing is the following:
SwiftData/BackingData.swift:409: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://34EE9059-A7B5-4484-96A0-D10786AC9FB0/TestApp/p2), implementation: SwiftData.PersistentIdentifierImplementation)
The same issue also happens when I try to retrieve a model from the ModelContext using its PersistentIdentifier and try to do anything with it. I have no idea what could be causing this.
I'm guessing this is just a bug in the iOS 18 Beta, since I couldn't find a single discussion about this on Google, I figured I'd mention it.
if someone has a workaround or something, that would be much appreciated.
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?
Hello,
I recently published an app that uses Swift Data as its primary data storage. The app uses concurrency, background threads, async await, and BLE communication.
Sadly, I see my app incurs many fringe crashes, involving EXC_BAD_ACCESS, KERN_INVALID_ADDRESS, EXC_BREAKPOINT, etc.
I followed these guidelines:
One ModelContainer that is stored as a global variable and used throughout.
ModelContexts are created separately for each task, changes are saved manually, and models are not passed around.
Threads with different ModelContexts might manipulate and/or read the same data simultaneously.
I was under the impression this meets the usage requirements.
I suspect perhaps the issue lies in my usage of contexts in a single await function, that might be paused and resumed on a different thread (although same execution path). Is that the case? If so, how should SwiftData be used in async scopes?
Is there anything else particularly wrong in my approach?
relationshipKeyPathsForPrefetching in SwiftData does not seem to work here when scrolling down the list. Why?
I would like all categories to be fetched while posts are fetched - not while scrolling down the list.
struct ContentView: View {
var body: some View {
QueryList(
fetchDescriptor: withCategoriesFetchDescriptor
)
}
var withCategoriesFetchDescriptor: FetchDescriptor<Post> {
var fetchDescriptor = FetchDescriptor<Post>()
fetchDescriptor.relationshipKeyPathsForPrefetching = [\.category]
return fetchDescriptor
}
}
struct QueryList: View {
@Query
var posts: [Post]
init(fetchDescriptor: FetchDescriptor<Post>) {
_posts = Query(fetchDescriptor)
}
var body: some View {
List(posts) { post in
VStack {
Text(post.title)
Text(post.category?.name ?? "")
.font(.footnote)
}
}
}
}
@Model
final class Post {
var title: String
var category: Category?
init(title: String) {
self.title = title
}
}
@Model final class Category {
var name: String
init(name: String) {
self.name = name
}
}
It takes a few seconds, sometimes a few minutes for records to be downloaded back from CloudKit when the user reinstalls the app, which leads users to thinking their data was lost. I would like to know if there’s any way to provide a visual feedback about the current CloudKit sync status so I can let users know their data is being in fact downloaded back to their devices.
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?