iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

CloudKit is not synchronizing with coredata for relationships
In core-data I have a contact and location entity. I have one-to-many relationship from contact to locations and one-to-one from location to contact. I create contact in a seperate view and save it. Later I create a location, fetch the created contact, and save it while specifying the relationship between location and contact contact and test if it actually did it and it works. viewContext.perform { do { // Set relationship using the generated accessor method currentContact.addToLocations(location) try viewContext.save() print("Saved successfully. Locations count:", currentContact.locations?.count ?? 0) if let locs = currentContact.locations { print("📍 Contact has \(locs.count) locations.") for loc in locs { print("➡️ Location: \(String(describing: (loc as AnyObject).locationName ?? "Unnamed"))") } } } catch { print("Failed to save location: \(error.localizedDescription)") } } In my NSManagedObject class properties I have this : for Contact: @NSManaged public var locations: NSSet? for Location: @NSManaged public var contact: Contact? in my persistenceController I have: for desc in [publicStore, privateStore] { desc.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) desc.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) desc.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption) desc.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption) desc.setOption(true as NSNumber, forKey: "CKSyncCoreDataDebug") // Optional: Debug sync // Add these critical options for relationship sync desc.setOption(true as NSNumber, forKey: "NSPersistentStoreCloudKitEnforceRecordExistsKey") desc.setOption(true as NSNumber, forKey: "NSPersistentStoreCloudKitMaintainReferentialIntegrityKey") // Add this specific option to force schema update desc.setOption(true as NSNumber, forKey: "NSPersistentStoreRemoteStoreUseCloudKitSchemaKey") } When synchronization happens on CloudKit side, it creates CKRecords: CD_Contact and CD_Location. However for CD_Location it creates the relationship CD_contact as a string and references the CD_Contact. This I thought should have come as REFERENCE On the CD_Contact there is no CD_locations field at all. I do see the relationships being printed on coredata side but it does not come as REFERENCE on cloudkit. Spent over a day on this. Is this normal, what am I doing wrong here? Can someone advise?
0
0
68
Apr ’25
SwiftData - disable Persistent History Tracking
Hello, I am building a pretty large database (~40MB) to be used in my SwiftData iOS app as read-only. While inserting and updating the data, I noticed a substantial increase in size (+ ~10MB). A little digging pointed to ACHANGE and ATRANSACTION tables that apparently are dealing with Persistent History Tracking. While I do appreciate the benefits of that, I prefer to save space. Could you please point me in the right direction?
0
0
62
Apr ’25
Mac App Crashing with Illegal Instructions
I have made a Swift App for MacOS 15 under XCode 16.3, which runs fine. I also want to run it under the previous MacOS 14. Unfortunately it crashes without even starting up (it does not even reach the first log output statement on the first view) The crash reason is Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [2970] I have set the miminium deployment to MacOS 14.0 but to no effect. The XCode machine is a MacOS 15.4 on Arm M3 and the target machine is MacOS 14.7.5 on Intel (MacBook Air) I think it might be related to the compiler and linker settings.
3
0
69
Apr ’25
SwiftData crashes on fetchHistory
Hi, would it be possible that instead of crashing when calling fetchHistory that function simply throws an error instead? fetchHistory seems to crash when it cannot understand the models if they are not compatible etc… which is understandable, but it makes it really difficult to handle and debug, there's not a lot of details, and honestly I would just rather that it throws an error and let me ignore a history entry that might be useless rather than crashing the entire app. Thank you!
1
1
56
Apr ’25
SwiftData iOS18: "Could not materialize Objective-C class named "Set" from declared attribute value type "Set<String>" of attribute named..."
Posting here to see if folks have workarounds or if I have a misunderstanding of SwiftData supported types. In adopting SwiftData, I have swiftData properties of collection type (Array or Set - both have this issue). E.g: @Model final class Item { var timestamp: Date var strings = ["aa", "bb"] var display: String { strings.joined(separator: " ") } init(timestamp: Date) { self.timestamp = timestamp } } So far in development I haven't had issues on iOS 17, but on the iOS 18 betas 4-5 the app logs show the following error: "fault: Could not materialize Objective-C class named "Array" from declared attribute value type "Array<String>" of attribute named strings" It happens immediately in my app when creating an object with a collection attribute. In a minimal test example, the error log appears only after a few minutes and doesn't seem to affect the template app's basic functionality. Anyone else running into this? Was filed as FB14397250
8
13
2.5k
Apr ’25
Debugging help
No matter what I do, I keep getting the error Thread 1: EXC_BREAKPOINT (code=1, subcode=0x2648fc364) for the line: transactions = try modelContext.fetch(descriptor) in the code below. My app opens, but freezes on the home page and I can't click anything. I am not sure how to fix initialization issues. I am creating a financial assistant app that connects plaid and opoenai api. var descriptor = FetchDescriptor&lt;ExpenseTransaction&gt;() descriptor.sortBy = [SortDescriptor(\.date, order: .reverse)] descriptor.fetchLimit = 200 transactions = try modelContext.fetch(descriptor) print("Successfully loaded \(transactions.count) transactions") } catch { print("Error in loadLocalTransactions: \(error)") transactions = [] } }
3
0
75
Apr ’25
SwiftData and iCloud
I'm a first time developer for Swift, (getting on a bit!) but after programming in VB back in the late 90s I wanted to write an app for iPhone. I think I might have gone about it the wrong way, but I've got an app that works great on my iPhone or works great on my iPad. It saves the data persistently on device, but, no matter how much I try, what I read and even resorting to AI (ChatGPT & Gemini) I still can't get it to save the data on iCloud to synchronise between the two and work across the devices. I think it must be something pretty fundamental I'm doing (or more likely not doing) that is causing the issue. I'm setting up my signing and capabilities as per the available instructions but I always get a fatal error. I think it might be something to do with making fields optional, but at this point I'm second guessing myself and feeling a complete failure. Any advice or pointers would be really gratefully appreciated. I like my app and would like eventually to get it on the App Store but at this point in time I feel it should be on the failed projects heap! I've even tried a new Xcode project for iOS and asking it to use SwiftData and CloudKit - the default project should work - right? But it absolutely doesn't for me. Please send help!!
2
0
116
Apr ’25
How is Record Zone Sharing done?
My use case is the following: Every user of my app can create as an owner a set of items.  These items are private until the owner invites other users to share all of them as participant. The participants can modify the shared items and/or add other items. So, sharing is not done related to individual items, but to all items of an owner. I want to use CoreData & CloudKit to have local copies of private and shared items. To my understanding, CoreData & CloudKit puts all mirrored items in a special zone „com.apple.coredata.cloudkit.zone“. So, this zone should be shared, i.e. all items in it. In the video it is said that NSPersistentCloudKitContainer uses Record Zone Sharing optionally in contrast to hierarchically record sharing using a root record. But how is this done? Maybe I can declare zone „com.apple.coredata.cloudkit.zone“ as a shared zone?
2
0
959
Apr ’25
SwiftData and @Query to find all records for the current date of a multidatepicker (Set = [])
I’m trying to build a CRUD app using SwiftData, @Query model and multidatepicker. The data from a multidatepicker is stored or persists in SwiftData as Set = []. My current dilemma is how to use SwiftData and @Query model Predicate to find all records on the current date. I can’t find any SwiftData documentation or examples @Query using Set = []. My CRUD app should retrieve all records for the current date. Unfortunately, I don’t know the correct @Query model syntax for Set = [].
0
0
46
Apr ’25
SwiftData JSONDataStore with relationships
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, "Create a custom data store with SwiftData", and (once updated for API changes since WWDC) that works fine. However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship? Here's my code; firstly the cleaned up code from the WWDC session: import SwiftData final class JSONStoreConfiguration: DataStoreConfiguration { typealias Store = JSONStore var name: String var schema: Schema? var fileURL: URL init(name: String, schema: Schema? = nil, fileURL: URL) { self.name = name self.schema = schema self.fileURL = fileURL } static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool { return lhs.name == rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) } } final class JSONStore: DataStore { typealias Configuration = JSONStoreConfiguration typealias Snapshot = DefaultSnapshot var configuration: JSONStoreConfiguration var name: String var schema: Schema var identifier: String init(_ configuration: JSONStoreConfiguration, migrationPlan: (any SchemaMigrationPlan.Type)?) throws { self.configuration = configuration self.name = configuration.name self.schema = configuration.schema! self.identifier = configuration.fileURL.lastPathComponent } func save(_ request: DataStoreSaveChangesRequest<DefaultSnapshot>) throws -> DataStoreSaveChangesResult<DefaultSnapshot> { var remappedIdentifiers = [PersistentIdentifier: PersistentIdentifier]() var serializedData = try read() for snapshot in request.inserted { let permanentIdentifier = try PersistentIdentifier.identifier(for: identifier, entityName: snapshot.persistentIdentifier.entityName, primaryKey: UUID()) let permanentSnapshot = snapshot.copy(persistentIdentifier: permanentIdentifier) serializedData[permanentIdentifier] = permanentSnapshot remappedIdentifiers[snapshot.persistentIdentifier] = permanentIdentifier } for snapshot in request.updated { serializedData[snapshot.persistentIdentifier] = snapshot } for snapshot in request.deleted { serializedData[snapshot.persistentIdentifier] = nil } try write(serializedData) return DataStoreSaveChangesResult<DefaultSnapshot>(for: self.identifier, remappedIdentifiers: remappedIdentifiers) } func fetch<T>(_ request: DataStoreFetchRequest<T>) throws -> DataStoreFetchResult<T, DefaultSnapshot> where T : PersistentModel { if request.descriptor.predicate != nil { throw DataStoreError.preferInMemoryFilter } else if request.descriptor.sortBy.count > 0 { throw DataStoreError.preferInMemorySort } let objs = try read() let snapshots = objs.values.map({ $0 }) return DataStoreFetchResult(descriptor: request.descriptor, fetchedSnapshots: snapshots, relatedSnapshots: objs) } func read() throws -> [PersistentIdentifier : DefaultSnapshot] { if FileManager.default.fileExists(atPath: configuration.fileURL.path(percentEncoded: false)) { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let data = try decoder.decode([DefaultSnapshot].self, from: try Data(contentsOf: configuration.fileURL)) var result = [PersistentIdentifier: DefaultSnapshot]() data.forEach { s in result[s.persistentIdentifier] = s } return result } else { return [:] } } func write(_ data: [PersistentIdentifier : DefaultSnapshot]) throws { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let jsonData = try encoder.encode(data.values.map({ $0 })) try jsonData.write(to: configuration.fileURL) } } The data model classes: import SwiftData @Model class Settings { private(set) var version = 1 @Relationship(deleteRule: .cascade) var hack: Hack? = Hack() init() { } } @Model class Hack { var foo = "Foo" var bar = 42 init() { } } Container: lazy var mainContainer: ModelContainer = { do { let url = // URL to file let configuration = JSONStoreConfiguration(name: "Settings", schema: Schema([Settings.self, Hack.self]), fileURL: url) return try ModelContainer(for: Settings.self, Hack.self, configurations: configuration) } catch { fatalError("Container error: \(error.localizedDescription)") } }() Load function, that saves a new Settings JSON file if there isn't an existing one: @MainActor func loadSettings() { let mainContext = mainContainer.mainContext let descriptor = FetchDescriptor<Settings>() let settingsArray = try? mainContext.fetch(descriptor) print("\(settingsArray?.count ?? 0) settings found") if let settingsArray, let settings = settingsArray.last { print("Loaded") } else { let settings = Settings() mainContext.insert(settings) do { try mainContext.save() } catch { print("Error saving settings: \(error)") } } } The save operation creates a JSON file, which while it isn't a format I would choose, is acceptable, though I notice that the "hack" property (the relationship) doesn't have the correct identifier. When I run the app again to load the data, I get an error (that there wasn't room to include in this post). Even if I change Apple's code to not assign a new identifier, so the relationship property and its pointee have the same identifier, it still doesn't load. Am I doing something obviously wrong, or are relationships not supported in custom data stores?
2
0
683
Apr ’25
SwiftData "Auto Inserts" array into ModelContext
Definitely one of the stranger quirks of SwiftData I've come across. I have a ScriptView that shows Line entities related to a Production, and a TextEnterScriptView that’s presented in a sheet to input text. I’m noticing that every time I type in the TextEditor within TextEnterScriptView, a new Line shows up in ScriptView — even though I haven’t explicitly inserted it into the modelContext. I'm quite confused because even though I’m only assigning a new Line to a local @State array in TextEnterScriptView, every keystroke in the TextEditor causes a duplicate Line to appear in ScriptView. In other words, Why is SwiftData creating new Line entities every time I type in the TextEditor, even though I’m only assigning to a local @State array and not explicitly inserting them into the modelContext? Here is my minimal reproducible example: import SwiftData import SwiftUI @main struct testApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Line.self, isAutosaveEnabled: false) } } } struct ContentView: View { @Environment(\.modelContext) var modelContext @Query(sort: \Production.title) var productions: [Production] var body: some View { NavigationStack { List(productions) { production in NavigationLink(value: production) { Text(production.title) } } .navigationDestination(for: Production.self) { production in ScriptView(production: production) } .toolbar { Button("Add", systemImage: "plus") { let production = Production(title: "Test \(productions.count + 1)") modelContext.insert(production) do { try modelContext.save() } catch { print(error) } } } .navigationTitle("Productions") } } } struct ScriptView: View { @Query private var lines: [Line] let production: Production @State private var isShowingSheet: Bool = false var body: some View { List { ForEach(lines) { line in Text(line.content) } } .toolbar { Button("Show Sheet") { isShowingSheet.toggle() } } .sheet(isPresented: $isShowingSheet) { TextEnterScriptView(production: production) } } } struct TextEnterScriptView: View { @Environment(\.dismiss) var dismiss @State private var text = "" @State private var lines: [Line] = [] let production: Production var body: some View { NavigationStack { TextEditor(text: $text) .onChange(of: text, initial: false) { lines = [Line(content: "test line", production: production)] } .toolbar { Button("Done") { dismiss() } } } } } @Model class Production { @Attribute(.unique) var title: String @Relationship(deleteRule: .cascade, inverse: \Line.production) var lines: [Line] = [] init(title: String) { self.title = title } } @Model class Line { var content: String var production: Production? init(content: String, production: Production?) { self.content = content self.production = production } }
1
0
49
Apr ’25
SwiftData serious bug with relationships and CloudKit in iOS 18.0 (Xcode 16 Beta)
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.
3
0
793
Apr ’25
Sync an interactive widget's Core Data store with the main app (and iCloud)
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!
4
0
303
Apr ’25
SwiftData Many-To-Many Relationship: Failed to fulfill link PendingRelationshipLink
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.
1
0
94
Apr ’25
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"
1
0
56
Apr ’25
SwiftData Lightweight Migraton failed with VersionedSchema
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.
1
0
81
Apr ’25
Core Data crash while trying to merge
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)
1
0
49
Apr ’25
Safe way to query for the existence of a CKRecordZone?
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?
1
0
58
Apr ’25