iCloud & Data

RSS for tag

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

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

Unable to see data from a production environment
I am trying to test using Testflight and have set up a test with a user on an account I also own which is different to me developer account. The app I believe is running in production on a separate device and is working from a user point of view, however I am not able to query the data via the console. As I said I know the user id and password as tey are mine so even when I use the Act as user service it logs in but the query is empty. I'm assuming I'm not doing anything wrong its possibly an security issue that is preventing me accessing this account. My question to the group then is how do I verify the data that is being tested?
1
0
246
1w
modelContext.fetch() hits assert on release builds, but not on debug builds
Exact same app works fine in debug builds, but on release builds I see this stacktrace indicating that assert() was hit. Incident Identifier: *** Distributor ID: com.apple.TestFlight Hardware Model: iPhone14,3 Process: AuditOS [67847] Path: /private/var/containers/Bundle/Application/*** Identifier: *** Version: 1.0 (15) AppStoreTools: 16C5031b AppVariant: 1:iPhone14,3:18 Beta: YES Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: *** Date/Time: 2025-02-11 12:37:54.7801 -0600 Launch Time: 2025-02-11 12:37:33.1737 -0600 OS Version: iPhone OS 18.3 (22D63) Release Type: User Baseband Version: 4.20.03 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000019d388e2c Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [67847] Triggered by Thread: 0 Thread 0 Crashed: 0 libswiftCore.dylib 0x000000019d388e2c _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:147) 1 SwiftData 0x0000000261842e04 Schema.KeyPathCache.validateAndCache(keypath:on:) + 2628 (Schema.swift:0) 2 SwiftData 0x000000026178cac4 static PersistentModel.keyPathToString(keypath:) + 360 (DataUtilities.swift:36) 3 SwiftData 0x000000026184c9e4 static PersistentModel.fetchDescriptorKeyPathString(for:) + 36 (FetchDescriptor.swift:51) 4 SwiftData 0x00000002617b9770 closure #1 in PredicateExpressions.KeyPath.convert(state:) + 172 (FetchDescriptor.swift:458) 5 SwiftData 0x00000002617b7f48 PredicateExpressions.KeyPath.convert(state:) + 352 (FetchDescriptor.swift:438) 6 SwiftData 0x00000002617bb7ec protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.KeyPath<A, B> + 16 (<compiler-generated>:0) 7 SwiftData 0x00000002617baaa0 PredicateExpression.convertToExpressionOrPredicate(state:) + 716 (FetchDescriptor.swift:219) 8 SwiftData 0x00000002617ba6dc PredicateExpression.convertToExpression(state:) + 32 (FetchDescriptor.swift:237) 9 SwiftData 0x00000002617b7cfc PredicateExpressions.Equal.convert(state:) + 328 (:-1) 10 SwiftData 0x00000002617bba08 protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.Equal<A, B> + 64 (<compiler-generated>:0) 11 SwiftData 0x00000002617baaa0 PredicateExpression.convertToExpressionOrPredicate(state:) + 716 (FetchDescriptor.swift:219) 12 SwiftData 0x00000002617b7abc PredicateExpression.convertToPredicate(state:) + 28 (FetchDescriptor.swift:244) 13 SwiftData 0x00000002617b7190 nsFetchRequest<A>(for:in:) + 1204 (FetchDescriptor.swift:64) 14 SwiftData 0x0000000261783358 DefaultStore.fetch<A>(_:) + 292 (DefaultStore.swift:496) 15 SwiftData 0x000000026178322c protocol witness for DataStore.fetch<A>(_:) in conformance DefaultStore + 16 (<compiler-generated>:0) 16 SwiftData 0x00000002617847fc asDataStore #1 <A><A1>(_:) in closure #1 in ModelContext.fetch<A>(_:) + 3152 (ModelContext.swift:2590) 17 SwiftData 0x00000002617a74d8 partial apply for closure #1 in ModelContext.fetch<A>(_:) + 100 (<compiler-generated>:0) 18 SwiftData 0x00000002617a7438 closure #1 in ModelContext.enumerateFetchableStores<A>(_:_:) + 208 (ModelContext.swift:2527) 19 SwiftData 0x00000002617a731c specialized ModelContext.enumerateFetchableStores<A>(_:_:) + 200 (ModelContext.swift:2522) 20 SwiftData 0x00000002617a6f08 ModelContext.fetch<A>(_:) + 144 (ModelContext.swift:2534) 21 SwiftData 0x00000002617a6e70 dispatch thunk of ModelContext.fetch<A>(_:) + 56 (:-1) 22 AuditOS 0x00000001041af3f4 0x10419c000 + 78836 23 AuditOS 0x00000001041bebd5 0x10419c000 + 142293 24 AuditOS 0x00000001041bbbf5 0x10419c000 + 130037 25 AuditOS 0x00000001041d8be5 0x10419c000 + 248805 26 AuditOS 0x00000001041bde6d 0x10419c000 + 138861 27 libswift_Concurrency.dylib 0x00000001aa6bfe39 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:497) The code in question looks like this: func addRecord<T: MyDtoProtocol>(_ someDTO: T) async throws { var zone: ZoneModel? = nil let recordName = someDTO.recordNameType let fetchDescriptor = FetchDescriptor<T.ModelType> (predicate: #Predicate {$0.recordName == recordName}) > var localEntitites: [T.ModelType] = try modelContext.fetch(fetchDescriptor) <---- I have isolated crash to this line. Basically for each swiftdata model type I have associatedType for Data Transfer Object type and vice versa.
4
1
377
2w
Can't deploy CloudKit schema because of empty record? Why?
When I try to promote schema to production, I get following error: Cannot promote schema with empty type 'workspace', please delete the record type before attempting to migrate the schema again However, in hierarchical root record sharing, I think it should be completely legit use case where there is empty root record (in my case workspace) to which other records reference through ->parent reference. Am I missing something? Is this weird constraint imposed on CloudKit?
1
0
252
2w
Mapping model not found if the attribute has "Preserve after deletion" enabled
I am trying to migrate my Core Data model to a new version with a new attribute added to it. Since my app supports macOS 13 I am not able to use the newly introduced Staged migrations. After much digging I found that the app is not able to find the Mapping Model when one of the attribute has "Preserve after deletion" enabled. I have enabled migration debbuging using com.apple.CoreData.MigrationDebug 1 I am getting following error error: CoreData: error: (migration) migration failed with error Error Domain=NSCocoaErrorDomain Code=134140 "Persistent store migration failed, missing mapping model." What is the way out here?
6
0
367
2w
Documents folder of my app not shown in iCloud Drive in Finder
The problem is that the iCloud Drive directory of my app does not appear in my iCloud Drive in Finder despite the (I think) correct settings in my info.plist file (see below). In Terminal, I can see the folder and it also contains .txt files. What can I do to make the folder visible in Finder and the Files app? <key>NSUbiquitousContainers</key> <dict> <key>iCloud.vmk.NewsSwiper</key> <dict> <key>NSUbiquitousContainerIsDocumentScopePublic</key> <true/> <key>NSUbiquitousContainerName</key> <string>RSS-Filter</string> <key>NSUbiquitousContainerIdentifier</key> <string>iCloud.vmk.NewsSwiper</string> <key>NSUbiquitousContainerSupportedFolderLevels</key> <string>Any</string> </dict> </dict>
3
0
322
2w
SwiftData propertiesToFetch question
I have a simple model @Model final class Movie: Identifiable { #Index\<Movie\>(\[.name\]) var id = UUID() var name: String var genre: String? init(name: String, genre: String?) { self.name = name self.genre = genre } } I turned on SQL debugging by including '-com.apple.CoreData.SQLDebug 3' argument on launch. When I fetch the data using the following code, it selects 3 records initially, but then also selects each record individually even though I am not referencing any other attributes. var fetchDescriptor = FetchDescriptor\<Movie\>() fetchDescriptor.propertiesToFetch = \[.id, .name\] fetchDescriptor.fetchLimit = 3 do { print("SELECT START") movies = try modelContext.fetch(fetchDescriptor) print("SELECT END") } catch { print("Failed to load Movie model.") } I see it selecting the 3 rows initially, but then it selects each one separately. Why would it do this on the initial fetch? I was hoping to select the data that I want to display and let the system select the entire record only when I access a variable that I did not initially fetch. CoreData: annotation: fetch using NSSQLiteStatement <0x600002158af0> on entity 'Movie' with sql text 'SELECT 1, t0.Z_PK, t0.ZID, t0.ZNAME FROM ZMOVIE t0 LIMIT 3' returned 3 rows with values: ( "<NSManagedObject: 0x600002158d70> (entity: Movie; id: 0xa583c7ed484691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p1>; data: <fault>)", "<NSManagedObject: 0x600002158d20> (entity: Movie; id: 0xa583c7ed482691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p2>; data: <fault>)", "<NSManagedObject: 0x600002158f00> (entity: Movie; id: 0xa583c7ed480691c1 <x-coredata://71E60F4C-1A40-4DB7-8CD1-CD76B4C11949/Movie/p3>; data: <fault>)" ) CoreData: annotation: fetch using NSSQLiteStatement <0x600002154d70> on entity 'Movie' with sql text 'SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZGENRE, t0.ZID, t0.ZNAME FROM ZMOVIE t0 WHERE t0.Z_PK = ? ' returned 1 rows CoreData: annotation: with values: ( "<NSSQLRow: 0x600000c89500>{Movie 1-1-1 genre=\"Horror\" id=4C5CB4EB-95D7-4DC8-B839-D4F2D2E96ED0 name=\"A000036\" and to-manys=0x0}" ) This all happens between the SELECT START and SELECT END print statements. Why is it fulfilling the faults immediately?
2
0
235
2w
Is there a guaranteed order for records in CKSyncEngine's handleFetchedRecordZoneChanges?
I have two recordTypes in CloudKit: Author and Book. The Book records have their parent property set to an Author, enabling hierarchical record sharing (i.e., if an Author record is shared, the participant can see all books associated with that author in their shared database). When syncing with CKSyncEngine, I was expecting handleFetchedRecordZoneChanges to deliver all Author records before their associated Book records. However, unless I’m missing something, the order appears to be random. This randomness forces me to handle two codepaths in my app (opposed to just one) to replicate CloudKit references in my local persistency storage: Book arrives before its Author → I store the Book but defer setting its parent reference until the corresponding Author arrives. Author arrives before its Books → I can immediately set the parent reference when each Book arrives. Is there a way to ensure that Author records always arrive before Book records when syncing with CKSyncEngine? Or is this behavior inherently unordered and I have to implement two codepaths?
1
0
303
2w
CKSyncEngine: Duplicate FetchedRecordZoneChanges & Sync Handling Questions
Hi everyone, I've recently implemented CKSyncEngine in my app, and I have two questions regarding its behavior: Duplicate FetchedRecordZoneChanges After Sending Changes: I’ve noticed that the engine sometimes receives a FetchedRecordZoneChanges event containing modifications and deletions that were just sent by the same device a few moments earlier. This event arrives after the SentRecordZoneChanges event, and both events share the same recordChangeTag, which results in double-handling the record. Is this expected behavior? I’d like to confirm if this is how CKSyncEngine works or if I might be overlooking something. Handling Initial Sync with a "Sync Screen": When a user opens the app for the first time and already has data stored in iCloud, I need to display a "Sync Screen" temporarily to prevent showing partial data or triggering abrupt, rapid UI changes. I’ve found that canceling current operations, then awaiting sendChanges() and fetchChanges() works well to ensure data is fully synced before dismissing the sync screen: displaySyncScreen = true await syncEngine.cancelOperations() try await syncEngine.sendChanges() try await syncEngine.fetchChanges() displaySyncScreen = false However, I’m unsure if canceling operations like this could lead to data loss or other issues. Is this a safe approach, or would you recommend a better strategy for handling this initial sync state?
1
0
268
2w
CoreData error=134100 Failed to open the store
Hello, I'm using CoreData + CloudKit and I am facing the following error 134100 "The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store." All my schema updates are composed of adding optional attributes to existing entities, adding non-optional attributes (with default value) to existing entities or adding new entities Basically, only things that lightweight migrations can handle. Every time I update the schema, I add a new model version of xcdatamodel - who only has a single configuration (the "Default" one). And I also deploy the updated CloudKit schema from the dashboard. It worked up to v3 of my xcdatamodel, but started to crash for a few users at v4 when I added 16 new attributes (in total) to 4 existing entities. Then again at v5 when I added 2 new optional attributes to 1 existing entity. I'm using a singleton and here is the code: private func generateCloudKitContainer() -> NSPersistentCloudKitContainer { let container = NSPersistentCloudKitContainer(name: "MyAppModel") let fileLocation = URL(...) let description = NSPersistentStoreDescription(url: fileLocation) description.shouldMigrateStoreAutomatically = true description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) let options = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.company.MyApp") options.databaseScope = .private description.cloudKitContainerOptions = options container.persistentStoreDescriptions = [description] container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores { description, error in container.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) if let error { // Error happens here! } } return container } I can't reproduce it yet. I don't really understand what could lead to this error.
4
0
428
3w
How to get a real time and date (not device time) for query?
I need to know the current date to query CloudKit data with it, like: let predicate = NSPredicate(format: "publishedAt <= %@", currentDateAndTime) I don't need high precision, even +/- a few minutes is fine, but I can't rely on device's time since the user can manually change it. Researching this myself I see that the most reliable method is to get the date from the server. There are NTP servers, but accessing them requires additional libraries which adds complexity. TrueTime (last updated 6 years ago) and Kronos (updated like once a year) seem outdated, given how much Swift has changed in the past years. I can make an HTTP request to a website like Google or Apple and read the current time from its headers. But I don't know if this method is reliable. I know I can create a dummy record in CloudKit, update it, and read its modificationDate. But it feels hacky. Maybe there is another way to fetch the current date directly from CloudKit? It feels like it should be easy and there is a straightforward solution, but I just can't find it.
1
0
294
3w
NSFetchedResultsController index out of bounds during context merging changes
I've noticed several crashes that look like they're caused by an index out of bound in internal methods of NSFetchedResultsController. This happens while changes are merged from the persistent store container into the view context. Here's an example of the last exception backtrace. Exactly which internal methods that are called in - [NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] vary between crash reports but they all end up crashing from _NSArrayRaiseBoundException. The Core Data stack consists of one persistent store, one persistent store coordinator that the view context is set up to automatically merge changes from, and data is saved to disk from background context. persistentContainer.loadPersistentStores(...) viewContext = persistentContainer.viewContext viewContext.automaticallyMergesChangesFromParent = true backgroundContext = persistentContainer.newBackgroundContext() backgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy backgroundClientContext = persistentContainer.newBackgroundContext() backgroundClientContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy Does anyone have any ideas what could be causing this? Thankful for any ideas or advice on how to investigate further.
2
0
356
3w
CoreData/CloudKit 0xdead10cc
I’m getting a 0xdead10cc crash in a basic CoreData/CloudKit application. I only have one CoreData save call and its made when the app is in the foreground and it's minor so I don't think its being caused by that. My best guess is that it's related to background syncing of CloudKit. Does anyone know how to fix it? I've been advised that adding the following code around any saves will fix it, but it seems weird that this is the solution. I would expect the inner CoreData/CloudKit engine to handle this. ProcessInfo().performActivity(reason: "Persisting to context") { // Save to context here } Here is the crashing thread Thread 7: 0 libsystem_kernel.dylib 0x00000001edc086f4 guarded_pwrite_np + 8 (:-1) 1 libsqlite3.dylib 0x00000001ca71b6e4 seekAndWrite + 456 (sqlite3.c:44287) 2 libsqlite3.dylib 0x00000001ca6d5df4 unixWrite + 180 (sqlite3.c:44365) 3 libsqlite3.dylib 0x00000001ca723b90 pagerWalFrames + 872 (sqlite3.c:67093) 4 libsqlite3.dylib 0x00000001ca6d5b14 sqlite3PagerCommitPhaseOne + 316 (sqlite3.c:70409) 5 libsqlite3.dylib 0x00000001ca6c6494 sqlite3BtreeCommitPhaseOne + 172 (sqlite3.c:81106) 6 libsqlite3.dylib 0x00000001ca6c605c vdbeCommit + 1136 (sqlite3.c:94124) 7 libsqlite3.dylib 0x00000001ca69f778 sqlite3VdbeHalt + 1340 (sqlite3.c:94534) 8 libsqlite3.dylib 0x00000001ca6c0618 sqlite3VdbeExec + 42648 (sqlite3.c:103922) 9 libsqlite3.dylib 0x00000001ca6b56c0 sqlite3_step + 960 (sqlite3.c:97886) 10 CoreData 0x00000001a459ab38 _execute + 128 (NSSQLiteConnection.m:4614) 11 CoreData 0x00000001a45fe004 -[NSSQLiteConnection commitTransaction] + 728 (NSSQLiteConnection.m:3278) 12 CoreData 0x00000001a469888c _executeGenerateObjectIDRequest + 388 (NSSQLCore_Functions.m:6021) 13 CoreData 0x00000001a46986a4 -[NSSQLGenerateObjectIDRequestContext executeRequestCore:] + 28 (NSSQLObjectIDRequestContext.m:42) 14 CoreData 0x00000001a45fb380 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 240 (NSSQLStoreRequestContext.m:183) 15 CoreData 0x00000001a45fb0a8 __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 60 (NSSQLConnectionManager.m:307) 16 CoreData 0x00000001a45fafe0 __37-[NSSQLiteConnection performAndWait:]_block_invoke + 48 (NSSQLiteConnection.m:755) 17 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576) 18 libdispatch.dylib 0x00000001a43677fc _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104) 19 CoreData 0x00000001a45b5ba4 -[NSSQLiteConnection performAndWait:] + 176 (NSSQLiteConnection.m:752) 20 CoreData 0x00000001a45b5a68 -[NSSQLDefaultConnectionManager handleStoreRequest:] + 248 (NSSQLConnectionManager.m:302) 21 CoreData 0x00000001a45b5938 -[NSSQLCoreDispatchManager routeStoreRequest:] + 228 (NSSQLCoreDispatchManager.m:60) 22 CoreData 0x00000001a45b573c -[NSSQLCore dispatchRequest:withRetries:] + 172 (NSSQLCore.m:4044) 23 CoreData 0x00000001a46737b4 -[NSSQLCore _obtainPermanentIDsForObjects:withNotification:error:] + 1324 (NSSQLCore.m:2830) 24 CoreData 0x00000001a460ba98 -[NSSQLCore _prepareForExecuteRequest:withContext:error:] + 272 (NSSQLCore.m:2946) 25 CoreData 0x00000001a460a0f8 __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.547 + 8988 (NSPersistentStoreCoordinator.m:2995) 26 CoreData 0x00000001a45d6660 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 264 (NSPersistentStoreCoordinator.m:668) 27 CoreData 0x00000001a45ded28 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1200 (NSPersistentStoreCoordinator.m:2810) 28 CoreData 0x00000001a4655988 -[NSManagedObjectContext save:] + 984 (NSManagedObjectContext.m:1593) 29 CoreData 0x00000001a46f47dc __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke_2 + 352 (NSCKEvent.m:76) 30 CoreData 0x00000001a45c28f0 developerSubmittedBlockToNSManagedObjectContextPerform + 476 (NSManagedObjectContext.m:3984) 31 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576) 32 libdispatch.dylib 0x00000001a43677fc _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104) 33 CoreData 0x00000001a4615c34 -[NSManagedObjectContext performBlockAndWait:] + 308 (NSManagedObjectContext.m:4108) 34 CoreData 0x00000001a46f45ac __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke + 192 (NSCKEvent.m:66) 35 CoreData 0x00000001a4825e68 -[PFCloudKitStoreMonitor performBlock:] + 92 (PFCloudKitStoreMonitor.m:148) 36 CoreData 0x00000001a46f4394 +[NSCKEvent beginEventForRequest:withMonitor:error:] + 256 (NSCKEvent.m:61) 37 CoreData 0x00000001a47cc6ec __57-[NSCloudKitMirroringDelegate _performExportWithRequest:]_block_invoke + 260 (NSCloudKitMirroringDelegate.m:1433) 38 CoreData 0x00000001a47c9970 __92-[NSCloudKitMirroringDelegate _openTransactionWithLabel:assertionLabel:andExecuteWorkBlock:]_block_invoke + 72 (NSCloudKitMirroringDelegate.m:957) 39 libdispatch.dylib 0x00000001a4356248 _dispatch_call_block_and_release + 32 (init.c:1549) 40 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576) 41 libdispatch.dylib 0x00000001a435f5cc _dispatch_lane_serial_drain + 768 (queue.c:3934) 42 libdispatch.dylib 0x00000001a4360158 _dispatch_lane_invoke + 432 (queue.c:4025) 43 libdispatch.dylib 0x00000001a436b38c _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7193) 44 libdispatch.dylib 0x00000001a436abd8 _dispatch_workloop_worker_thread + 540 (queue.c:6787) 45 libsystem_pthread.dylib 0x0000000227213680 _pthread_wqthread + 288 (pthread.c:2696) 46 libsystem_pthread.dylib 0x0000000227211474 start_wqthread + 8 (:-1)
3
0
353
4w
Odd, transient .badContainer error in CloudKit
I'm beta-testing a CloudKit-based app. One of my testers suddenly reported that they got a .badContainer CloudKit error: <CKError 0x302619800:"Bad Container" (5/1014); server message = "Invalid container to get bundle ids"; op = <...>; uuid = <...>; container ID = "<...>"> (all private info replaced with <...>) The container ID in the message was exactly what I expected, and exactly what other users are successfully using. When I followed up on the report, the user said she tried again later and everything was fine. It's still working fine days later. What could cause a user to get a .badContainer message, when all other users using the same app are fine, the container ID makes sense, and future runs work fine? Is this something I need to worry about? Does it maybe sometimes happen when CloudKit is having some kind of outage?
1
0
316
4w
SwiftData crash when using a @Query sort descriptor with a relationship
I am using SwiftData for storage and have a view that uses the @Query property wrapper with a sort descriptor that points to a relationship on a model. In a release build on device running iOS 18.3, the app crashes. This is the line that crashes: @Query(sort: \Item.info.endDate, order: .reverse) private var items: [Item] Item has a relationship to ItemInfo, which is where the endDate property is defined. This code works in debug and on a simulator. In the project referenced here: https://github.com/lepolt/swiftdata-crash, change the scheme build configuration to “Release” and run on device. The app will crash. Using Xcode Version 16.2 (16C5032a) iPhone 12, iOS 18.3 (22D60)
5
9
635
4w
Data Protection and SwiftData Containers
SwiftData ModelContainer instances don't seem to have a value for setting the Data Protection class. Is the best way to set that by setting the Data Protection in the app capabilities? Is that the only way? I have a need for log data that would be "Complete unless open" and user data that would be "Complete", but how do I change one of the containers data protection class?
2
1
479
Jan ’25
Core Data slow to save
iOS 18.2, Swift, Xcode 16.2 I have a Core Data model with two entities - WarehouseArea (of which there is only one object) and StockReeipt (of which there are a couple of hundred thousand). Each StockReceipt must be linked to a WarehouseArea, and a WarehouseArea can be linked to zero, one or many StockReceipts. My problem is that when I create and add one more StockReceipt, the Core Data save takes over 3 seconds to complete. I don't understand why this is so slow. Saving the initial 200,000 StockReceipts only takes 5-6 seconds. When I enable SQL logging I can see that when the WarehouseArea attribute is being set on a StockReceipt, Core Data fetches all of the other StockReceipts (I don't know why) but that only takes 0.2 seconds and none of those StockReceipts are modified, so there shouldn't be any need to process them when saving the context. I have prepared a test project which can be found at https://github.com/DaleReilly/CoreDataSaveTester . Running the project will produce NSLog output showing the times before and after the slow save. Please help me understand what is going on in the background and tell me if there is any way I can speed this up?
3
0
404
Jan ’25
How to Drop Entity in SwiftData and CloudKit?
I'm using SwiftData with CloudKit and have been trying to migrate from SchemaV1 to SchemaV2, but it seems reducing the Entities crashes my app. // Example of migrating from V1 to V2 // Dropping `Person` because it's no longer needed do { // SchemaV1: Person.self, Author.self // SchemaV2: Author.self let schema = Schema(versionedSchema: SchemaV2.self) return try ModelContainer( for: schema, migrationPlan: AppSchemaMigrationPlan.self, configurations: ModelConfiguration( cloudKitDatabase: .automatic) ) } catch { fatalError("Could not create ModelContainer: \(error)") } Is it possible to drop Entities in the Schema Migration Plan? How can I delete the Person model from my Schema and CloudKit?
3
0
434
Jan ’25
SwiftData Relationship Delete Not Working (SwiftData/PersistentModel.swift:359)
SwiftData delete isn't working, when I attempt to delete a model, my app crashes and I get the following error: SwiftData/PersistentModel.swift:359: Fatal error: Cannot remove My_App.Model2 from relationship Relationship - name: model2, options: [], valueType: Model2, destination: Model2, inverseName: models3, inverseKeypath: Optional(\Model2.models3) on My_App.Model3 because an appropriate default value is not configured. I get that it's saying I don't have a default value, but why do I need one? Isn't @Relationship .cascade automatically deleting the associated models? And onto of that, why is the error occurring within the do block, shouldn't it be caught by the catch, and printed? I have put together a sample project below. import SwiftUI import SwiftData @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Model3.self) } } } @Model class Model1 { var name: String @Relationship(deleteRule: .cascade, inverse: \Model2.model1) var models2: [Model2] = [] init(name: String) { self.name = name } } @Model class Model2 { var name: String var model1: Model1 @Relationship(deleteRule: .cascade, inverse: \Model3.model2) var models3: [Model3] = [] init(name: String, model1: Model1) { self.name = name self.model1 = model1 } } @Model class Model3 { var name: String var model2: Model2 init(name: String, model2: Model2) { self.name = name self.model2 = model2 } } struct ContentView: View { @Query var models1: [Model1] @Environment(\.modelContext) var modelContext var body: some View { NavigationStack { List(models1) { model1 in Text(model1.name) .swipeActions { Button("Delete", systemImage: "trash", role: .destructive) { modelContext.delete(model1) do { try modelContext.save() //SwiftData/PersistentModel.swift:359: Fatal error: Cannot remove My_App.Model2 from relationship Relationship - name: model2, options: [], valueType: Model2, destination: Model2, inverseName: models3, inverseKeypath: Optional(\Model2.models3) on My_App.Model3 because an appropriate default value is not configured. } catch { print(error.localizedDescription) } } } } .toolbar { Button("Insert", systemImage: "plus") { modelContext.insert(Model3(name: "model3", model2: Model2(name: "model2", model1: Model1(name: "model1")))) } } } } }
1
0
455
Jan ’25