Core Data

RSS for tag

Save your application’s permanent data for offline use, cache temporary data, and add undo functionality to your app on a single device using Core Data.

Posts under Core Data tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI NavigationLink freezing when tapped
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
12
2
6.4k
3w
How does NSFetchRequest compare custom objects?
I have a CoreData-based app that's many years old, so it's been a long time since I've actually dealt with CoreData. Over recent years, I've noticed that fetch requests aren't finding the object I know is in there. The entity is called Folder and has a single attribute named url, which is of type Transformable. The transformer is a custom one that converts a url into a dictionary with 2 keys; one is a security scoped bookmark created from the url, and the other is the original url in case the bookmark fails. The dictionary is then converted to NSData using NSKeyedArchiver securely. The reverseTransformedValue does the opposite; unarchives the data to a dict, attempts to resolve the bookmark back into the url. The fetch request is set up to fetch all Folder objects where: Custom Predicate: url == $THE_URL So is the fetch request comparing the NSData that's stored in the file and comparing that to $THE_URL after running it through the transformer to arrive at an NSData, or is it running each one through the transformer to get the underlying url and comparing those with $THE_URL? Could there be a better way to compare urls in Core Data, when the app is sandboxed and must use security scoped bookmarks?
0
0
145
3w
error: CoreData+CloudKit: Never successfully initialized and cannot execute request - incomprehensible archive
anyone getting the following error with CloudKit+CoreData on iOS16 RC? delete/resintall app, delete user CloudKit data and reset of environment don't fix. [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2044): <NSCloudKitMirroringDelegate: 0x2816f89a0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283abfa00> 41E6B8D6-08C7-4C73-A718-71291DFA67E4' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}
3
0
1.2k
3w
Restart sync when using NSPersistentCloudKitContainer
It's 2024, and it still seems like the only sure way to cleanly restart cloud sync on an app using NSPersistentCloudKitContainer is to uninstall and reinstall the app. No need to describe how bad that solution is... Am I missing something? Is there a better way to safely trigger such a restart of the sync (even if it means losing unsaved data and overwriting with what's in the cloud - which is what a reinstall does anyway)?
2
0
322
3w
CloudKit Stopped Syncing after adding new Entities
Can someone please shed some light? I have an app that uses Core Data and CloudKit, up until the last version, I was able to sync data between devices but now after I added two new Entities for some reason it stopped syncing between devices. Here is how I did the change: Created a new Core Data container. Added the new Entities and their Attributes Tested the new Entities locally to be able to send the new schema to CloudKit. Went to CloudKit and made sure that the new Entities and Attributes were reflected on the Developent database. Deploy Schema Cahnges. Went to the Production database to make sure the new schema was deployed; and it was, both databases look the same. Testing: Tested in the simulator and with a real device and everything syncs, even the new Entities. If I download the app from the App Store on two different devices they do NOT sync. Based on the procedure I'm describing above, is there any important step I may have missed when doing the migration? I'm not sure if this is related to the syncing issue but after testing a few times, I no longer can turn the iCloud on, I get the following message when I try to turn iCloud Sync On. CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:]: <NSCloudKitMirroringDelegate: 0x282c488c0> - resetting internal state after error: Error Domain=NSCocoaErrorDomain Code=134410 "CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process." UserInfo={NSURL=file:///var/mobile/Containers/Data/Application/73F19BC7-4538-4098-85C7-484B36192CF3/Library/Application%20Support/CoreDataContainer.sqlite, NSLocalizedFailureReason=CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process., NSUnderlyingException=Illegal attempt to register a second handler for activity identifier com.apple.coredata.cloudkit.activity.setup.8D4C04F6-8040-445A-9447-E5646484521} Any idea of what could be wrong and preventing the devices from syncing? Any idea or suggestion is welcome. Thanks
3
0
1.9k
3w
UIDocument related hang in OS code
Hi A user of my app has contacted me about a crash they’re getting. They’ve sent me some logs (see attached) but I’m having difficulty working out what the cause is as it looks like it’s a watchdog timeout that’s occurring inside OS code, not my application. I also can’t reproduce the crash locally. App background info: The app logs peoples skydives, each log can contain a lot of data (rotation rates, acceleration, location, speeds, etc) and is stored in a separate file. These files can be stored in an iCloud container so the logs can be viewed from different devices. I use CoreData to maintain a database of key metadata so I can list the jumps in the UI even if the file for a jump isn’t on the device. Occasionally I have to delete this database and rebuild it by loading each jump log file and getting a fresh copy of the metadata. EG this can happen if a new version of the app requires an additional metadata field in the database. Crash info: The crash looks like it’s happening rebuilding the database, so the app will be trying to download and open each jump log and add the records to the database. I’ve noticed the following odd things about the crash log, which might be a good place to start: There’s a huge number of threads in the “”UIDocument File Access” dispatch queue that are blocked It looks like there's exactly 512 threads blocked in this queue. Which makes me think its hitting a limit. Any idea why they are blocked? I don’t know why there are so many, The database rebuild is done from an operation queue with a max concurrency of 10. So I would expect at most 10 jump logs to be being opened at one time There seams to be two common stack trace patterns. Eg compare thread 1 and thread 5 in crash log 1. In both crash logs the main thread is blocked, but in different bits of OS code in the two crash logs. It looks like this is the cause of the watchdog failure, but I’m not sure what the common cause could be. Any ideas / help would be really appreciated. Thanks Tom NOTE: I had to cut down the crash logs so they were small enough to upload. Crash log 1 small.txt Crash log 2 small.txt
0
0
163
3w
Using Core Data with the Swift 6 language mode
I'm starting to work on updating my code for Swift 6. I have a number of pieces of code that look like this: private func updateModel() async throws { try await context.perform { [weak self] in // do some work } } After turning on strict concurrency checking, I get warnings on blocks like that saying "Sending 'self.context' risks causing data races; this is an error in the Swift 6 language mode." What's the best way for me to update this Core Data code to work with Swift 6?
4
1
580
4w
SwiftData crash: PersistentModel.keyPathToString(keypath:)
I'm distributing an iOS (17.4+) and visionOS (1.2+) app via TestFlight that's using SwiftData. The most common crash by far is from SwiftData when deleting models from a context using a predicate (first snippet below), but so far I've been unable to reproduce it myself locally (second snippet below). I'm using SwiftData outside of SwiftUI views, via my own wrapper, and converting between my app models and SwiftData models. Does anyone have any ideas how I could potentially narrow this issue down (or reproduce), or know of any similar issues? Thanks! — Seb do { try context.transaction { context in let predicate = #Predicate<PersistedFeed> { $0.id == id } do { try context.delete(model: PersistedFeed.self, where: predicate) } catch { // .. Omitted for brevity } } } catch { // .. Omitted for brevity } Crash: Thread 0 Crashed: 0 libswiftCore.dylib 0x000000018dd558c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 SwiftData 0x000000022f7f323c static PersistentModel.keyPathToString(keypath:) + 1496 (DataUtilities.swift:0) 2 SwiftData 0x000000022f83312c PredicateExpressions.KeyPath.convert(state:) + 492 (FetchDescriptor.swift:394) 3 SwiftData 0x000000022f834a24 protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.KeyPath<A, B> + 16 (<compiler-generated>:0) 4 SwiftData 0x000000022f830a70 PredicateExpression.convertToExpressionOrPredicate(state:) + 724 (FetchDescriptor.swift:203) 5 SwiftData 0x000000022f831874 PredicateExpression.convertToExpression(state:) + 36 (FetchDescriptor.swift:217) 6 SwiftData 0x000000022f83b6c8 PredicateExpressions.Equal.convert(state:) + 328 7 SwiftData 0x000000022f8360ec protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.Equal<A, B> + 64 (<compiler-generated>:0) 8 SwiftData 0x000000022f830a70 PredicateExpression.convertToExpressionOrPredicate(state:) + 724 (FetchDescriptor.swift:203) 9 SwiftData 0x000000022f82fd60 PredicateExpression.convertToPredicate(state:) + 28 (FetchDescriptor.swift:224) 10 SwiftData 0x000000022f82edb4 nsPredicate<A>(for:) + 956 (FetchDescriptor.swift:88) 11 SwiftData 0x000000022f807c2c ModelContext.delete<A>(model:where:includeSubclasses:) + 596 (ModelContext.swift:1846) 12 SwiftData 0x000000022f81994c dispatch thunk of ModelContext.delete<A>(model:where:includeSubclasses:) + 56
0
0
208
4w
Xcode 15: Core Data : No NSValueTransformer with class name *** was found for attribute YYY on entity ZZZ for custom `NSSecureUnarchiveFromDataTransformer`
Hi, I am creating a custom NSSecureUnarchiveFromDataTransformer in order to handle attributes of entities of type NSDateComponents. It all works and I did not see any warnings in the "Issue navigator" inside Xcode but with Xcode 15 I started seeing this warning: /Users/.../CustomNSSecureUnarchiveFromDataTransformer/CoreData:1:1 no NSValueTransformer with class name 'CustomSecureUnarchiveFromDataTransformer' was found for attribute 'testDate' on entity 'Item' My use case is very simple, I have this custom transformer: @objc(CustomSecureUnarchiveFromDataTransformer) final class CustomSecureUnarchiveFromDataTransformer: NSSecureUnarchiveFromDataTransformer { override class var allowedTopLevelClasses: [AnyClass] { return [NSDateComponents.self] } static let name = NSValueTransformerName(rawValue: String(describing: CustomSecureUnarchiveFromDataTransformer.self)) public static func register() { let transformer = CustomSecureUnarchiveFromDataTransformer() ValueTransformer.setValueTransformer(transformer, forName: name) } } which is set to the Core data entity's "Transformer": which leads to the warning in Xcode 15. App works just fine and there are no problems during run time, but this warning is shown and I want to fix it. Here is a simple test project https://github.com/VladimirAmiorkov/CustomNSSecureUnarchiveFromDataTransformer
12
10
2.6k
4w
Using NSFetchedResultsController with viewContext seems to have bad performance
Hello! Our team have been using a NSFetchedResultsController with viewContext for list UI. But we found some UI Hang logs, and I'm guessing that it happens because of Faulting in viewContext. The main thread call stacks in the logs look like below. 0 libsystem_kernel.dylib 0x00000001f378dbcc kevent_id + 8 1 libdispatch.dylib 0x00000001b4047b0f _dispatch_kq_poll + 227 2 libdispatch.dylib 0x00000001b40484df _dispatch_event_loop_wait_for_ownership + 435 3 libdispatch.dylib 0x00000001b4034983 __DISPATCH_WAIT_FOR_QUEUE__ + 339 4 libdispatch.dylib 0x00000001b403454b _dispatch_sync_f_slow + 147 5 CoreData 0x00000001b42859b3 _perform + 203 6 CoreData 0x00000001b4372767 -[NSManagedObjectContext+ 1275751 (_NestedContextSupport) newValuesForObjectWithID:withContext:error:] + 163 7 CoreData 0x00000001b424cf87 _PFFaultHandlerLookupRow + 275 8 CoreData 0x00000001b424cbbf _PF_FulfillDeferredFault + 191 9 CoreData 0x00000001b424cab7 _pvfk_header + 167 10 CoreData 0x00000001b424c9d7 _sharedIMPL_pvfk_core + 31 11 Works 0x000000010445517b closure #1 in static MailUIMailFactory.make(mail:needFolderName:) + 26530171 (MailUIMailFactory.swift:109) ... 0 libsystem_kernel.dylib 0x00000001dbd4254c kevent_id + 8 1 libdispatch.dylib 0x000000019b7057d3 _dispatch_kq_poll + 227 2 libdispatch.dylib 0x000000019b7061bb _dispatch_event_loop_wait_for_ownership + 435 3 libdispatch.dylib 0x000000019b6f2593 __DISPATCH_WAIT_FOR_QUEUE__ + 339 4 libdispatch.dylib 0x000000019b6f215b _dispatch_sync_f_slow + 147 5 CoreData 0x000000019b94f24b _perform + 203 6 CoreData 0x000000019ba3c41b -[NSManagedObjectContext+ 1274907 (_NestedContextSupport) newValueForRelationship:forObjectWithID:withContext:error:] + 167 7 CoreData 0x000000019b914387 -[NSFaultHandler retainedFulfillAggregateFaultForObject:andRelationship:withContext:] + 391 8 CoreData 0x000000019b9118bf -[_NSFaultingMutableSet willReadWithContents:] + 391 9 CoreData 0x000000019b91e663 -[_NSFaultingMutableSet count] + 23 10 Foundation 0x0000000192dbeb3f -[NSSet+ 7609151 (NSKeyValueSorting) sortedArrayUsingDescriptors:] + 55 11 Works 0x000000010249ec1f specialized static MailUIMailFactory.make(mail:needFolderName:) + 27470879 (MailUIMailFactory.swift:102) ... We just use NSFetchedResultsController's fetchedObjects in table view's cellForRowAt method, and make a new model by MailUIMailFactory.make. So we're thinking that we need to initialize NSFetchedResultsController with bg Context. What you guys think? Do I avoid using viewContext in heavy UI?
0
0
179
4w
How to embed SwiftData model container in a custom file package document type
Hi all, I have done a lot of research on this but am not able to come up with a workable solution. Background: I am trying to make an universal app on macOS/iOS that organizes media (image/video/pdf); think of its functionality like Apple's Photos app. So for my app document type, I would have my custom file package and within the package folder, there would be a SwiftData model container file and folders to hold user media. Approaches taken: DocumentGroup with SwiftData model then write directly into the file package In my App scene, I create document by having DocumentGroup(editing: .customDocument, migrationPlan: CustomMigrationPlan.self). This will create a document with a model container with my SwiftData model. And when I need to add media files into the document, I get the URL of the document, then use FileManager to write the file into the desired folder in the document. The result is that the media file is saved in the file package but then the SwiftData container is corrupted (all model data is reset to empty.) I am now trying to: 2. DocumentGroup with custom file package then try to embed SwiftData container In my current approach, I would create a document by having DocumentGroup(newDocument: CustomFileDocument()). I have custom FileDocument and FileWrapper. But the problem is I don't know how to embed a SwiftData container into my FileDocument. Is it possible to create a SwiftData model container when my FilerWrapper initialize? I can't figure out how to do this. Can anyone please advice on how I should accomplish this? Or if maybe I am looking at this problem wrongly? Do I need to use AppKit/UIKit with Core Data because it's currently not possible with SwiftUI/SwiftData? Thank you so much for reading and any input is greatly appreciated.
0
0
195
Jun ’24
SwiftUI List selection bug
Is there a way to optimize a List in SwiftUI? There is a problem with selection not working properly when the List has many rows. If you scroll to multi-select and up, some rows in the middle are not selected. I have an issue where selecting an unselected row deselects nearby rows. Is there any way for selection to work reliably even for a List of many rows? I would like to find a solution that is stable even when multiple lines are selected, like mail and note, which are the default apps in ios. ps. I am using CoreData. @State var selectedItem = Set<MyEntity>() List(selection: $selectItem){   ForEach(items, id: \.self){ item in     ContactsRow(contactsData: item)   } } .environment(\.editMode, $editMode)
1
0
1.3k
Jun ’24
Can the NSPersistentCloudKitContainer mirror the data from the cloudKit public database to the local Core Data if the user is not logged in?
I'm currently syncing Core Data with the CloudKit public database using NSPersistentCloudKitContainer. The app starts with an empty Core Data store locally and at the app launch it downloads the data from CloudKit public database to the Core Data store, but this can only be accomplished if the user is logged in, if the user is not logged, no data gets downloaded and I get the error below. Can the NSPersistentCloudKitContainer mirror the data from the CloudKit public database to the local Core Data even if the user is not logged in? Can someone please confirm this is possible? The reason for my question is because I was under the impression that the users didn't need to be logged to read data from the public database in CloudKit but I'm not sure this applies to NSPersistentCloudKitContainer when mirroring data. I know I can fetch data directly with CloudKit APIs without the user beign logged but I need to understand if NSPersistentCloudKitContainer should in theory work without the user being logged. I hope someone from Apple sees this question since I have spent too much time researching without any luck. Error Error fetching user record ID: <CKError 0x600000cb1b00: "Not Authenticated" (9); "No iCloud account is configured"> CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1192): <NSCloudKitMirroringDelegate: 0x600003b00460>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x10700f0d0> (URL: file:///Users/UserName/...
4
0
376
Jun ’24
Prevent Data Retention in Core Data When View is Dismissed
Prerequisite Information I am trying to use Core Data in my SwiftUI app. I have created 3 entities, a Record, a Header and an Entry. The Record contains the Header entities. The Header contain other Header or Entry entities. The Entry has a title and a value. My List view looks like this, I fetch the records with a @FetchRequest. NavigationView { List { ForEach(records) { record in NavigationLink(destination: DetailView(headers: record.headers!.allObjects as? [Header] ?? [], isNewEntry: true)) { Text(record.id!.uuidString) } } } } In my DetailView I have a form that passes the details to other views which create a DisclosureGroup for a Header, a bold Text for a subheader, and a TextField for an Entry let headers: [Header] let isNewEntry: Bool @Environment(\.managedObjectContext) var managedObjectContext init(headers: [Header], isNewEntry: Bool = false) { self.headers = headers self.isNewEntry = isNewEntry } Form { ForEach(Array(headers.enumerated()), id: \.element) { index, header in HeaderView(header: header, isExpanded: Binding( get: { self.expandedStates[header.id!, default: false] }, set: { self.expandedStates[header.id!] = $0 } )) } } Problem When I press the record in the list, it takes me to the DetailView where I can write something in the TextField. Then if I slide back and do not press the save button and then press the same record again from the list, it retains the data I wrote in the TextField. Question How can I make it so that the data is not retained if I slide back except only when I press the save button? Please let me know if any other information is needed or if something is unclear.
0
1
234
Jun ’24
NSFetchedResultsController - NSInvalidArgumentException
Good morning, I've developed an application where we download a JSON of objects and we store those information on a CoreData table. We've also created a Collection view used to show those information through a NSFetchedResultsController. Can someone helps me to understand the reason why I get this issue? Thanks indeed Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x83f20 __exceptionPreprocess 1 libobjc.A.dylib 0x16018 objc_exception_throw 2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException 3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:] 4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:] 5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects] 6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:] 7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke 8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:] 10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:] 11 CoreFoundation 0x5178c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ 12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke 13 CoreFoundation 0x515f0 _CFXRegistrationPost 14 CoreFoundation 0x4fbb8 _CFXNotificationPost 15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:] 16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] 17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] 18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:] 19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] 20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] 21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 22 libdispatch.dylib 0x3dd4 _dispatch_client_callout 23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain 24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF 25 CoreFoundation 0x56710 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ 26 CoreFoundation 0x53914 __CFRunLoopRun 27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific 28 GraphicsServices 0x11a8 GSEventRunModal 29 UIKitCore 0x40a90c -[UIApplication _run] 30 UIKitCore 0x4be9d0 UIApplicationMain 31 Rainbow 0x80c0 main + 15 (main.swift:15) 32 ??? 0x1b3419e4c (Mancante)
1
0
232
Jun ’24
Crash: NSFetchedResultsController NSInvalidArgumentException
Good morning, I've developed an application in order to show the information stored into a CoraData Table on a CollectionView through a NSFetchedResultsController. Several times I got this issue, is there anyone who can help me to understand the reason why this happens? Thanks indeed. Fatal Exception: NSInvalidArgumentException 0 CoreFoundation 0x83f20 __exceptionPreprocess 1 libobjc.A.dylib 0x16018 objc_exception_throw 2 CoreFoundation 0x1b6250 _NSArrayRaiseInsertNilException 3 CoreFoundation 0x16f5c -[__NSCFArray objectAtIndex:] 4 CoreData 0x13af14 -[_PFMutableProxyArray subarrayWithRange:] 5 CoreData 0xc4948 -[_NSDefaultSectionInfo objects] 6 CoreData 0x9c3fc -[NSFetchedResultsController _conditionallyDispatchSnapshotToDelegate:updatesInfo:] 7 CoreData 0x6d4ec __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke 8 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 9 CoreData 0x9d0ec -[NSManagedObjectContext performBlockAndWait:] 10 CoreData 0x9c6e8 -[NSFetchedResultsController _core_managedObjectContextDidChange:] 11 CoreFoundation 0x5178c CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER 12 CoreFoundation 0x516a8 ___CFXRegistrationPost_block_invoke 13 CoreFoundation 0x515f0 _CFXRegistrationPost 14 CoreFoundation 0x4fbb8 _CFXNotificationPost 15 Foundation 0x31574 -[NSNotificationCenter postNotificationName:object:userInfo:] 16 CoreData 0x6a548 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] 17 CoreData 0x69d10 -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] 18 CoreData 0x68a4c -[NSManagedObjectContext _processRecentChanges:] 19 CoreData 0x91494 -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] 20 CoreData 0x90334 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] 21 CoreData 0x270dc developerSubmittedBlockToNSManagedObjectContextPerform 22 libdispatch.dylib 0x3dd4 _dispatch_client_callout 23 libdispatch.dylib 0x125a4 _dispatch_main_queue_drain 24 libdispatch.dylib 0x121b8 _dispatch_main_queue_callback_4CF 25 CoreFoundation 0x56710 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE 26 CoreFoundation 0x53914 __CFRunLoopRun 27 CoreFoundation 0x52cd8 CFRunLoopRunSpecific 28 GraphicsServices 0x11a8 GSEventRunModal 29 UIKitCore 0x40a90c -[UIApplication _run] 30 UIKitCore 0x4be9d0 UIApplicationMain 31 Cloud 0x80c0 main + 15 (main.swift:15) 32 ??? 0x1b3419e4c (Mancante)
0
0
169
Jun ’24
Understanding Syncing between Core Data and CloudKit Public Database using NSPersistantCloudKitContainer
Can someone please give me an overview of how sync works between Core Data and the public CloudKit database when using the NSPersistentCloudKitContainer and please point out my misunderstandings based on what I describe below? In the following code, I'm successfully connecting to the public database in CloudKit using the NSPersistentCloudKitContainer. Below is how I have Core Data and CloudKit set up for your reference. In CloudKit I have a set of PublicIconImage that I created manually via the CloudKit Console. I intend to be able to download all images from the public database at the app launch to the local device and manage them via Core Data to minimize server requests, which works but only if the user is logged in. This is the behavior I see: When the app launches, all the CloudKit images get mirrored to Core Data and displayed on the screen but only if the user is logged in with the Apple ID, otherwise nothing gets mirrored. What I was expecting: I was under the impression that when connecting to the public database in CloudKit you didn't need to be logged in to read data. Now, if the user is logged in on the first launch, all data is successfully mirrored to Core Data, but then if the user logs off, all data previously mirrored gets removed from Core Data, and I was under the impression that since Core Data had the data already locally, it would keep the data already downloaded regardless if it can connect to CloudKit or not. What am I doing wrong? Core Data Model: Entity: PublicIconImage Attributes: id (UUID), imageName (String), image (Binary Data). CloudKit Schema in Public Database: Record: CD_PublicIconImage Fields: CD_id (String), CD_imageName (String), CD_image (Bytes). Core Data Manager class CoreDataManager: ObservableObject{ // Singleton static let instance = CoreDataManager() private let queue = DispatchQueue(label: "CoreDataManagerQueue") private var iCloudSync = true lazy var context: NSManagedObjectContext = { return container.viewContext }() lazy var container: NSPersistentContainer = { return setupContainer() }() func updateCloudKitContainer() { queue.sync { container = setupContainer() } } func setupContainer()->NSPersistentContainer{ let container = NSPersistentCloudKitContainer(name: "CoreDataContainer") guard let description = container.persistentStoreDescriptions.first else{ fatalError("###\(#function): Failed to retrieve a persistent store description.") } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) let cloudKitContainerIdentifier = "iCloud.com.example.PublicDatabaseTest" let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) description.cloudKitContainerOptions = options description.cloudKitContainerOptions?.databaseScope = .public // Specify Public Database container.loadPersistentStores { (description, error) in if let error = error{ print("Error loading Core Data. \(error)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return container } func save(){ do{ try context.save() }catch let error{ print("Error saving Core Data. \(error.localizedDescription)") } } } View Model Class class PublicIconImageViewModel: ObservableObject { let manager: CoreDataManager @Published var publicIcons: [PublicIconImage] = [] init(coreDataManager: CoreDataManager = .instance) { self.manager = coreDataManager loadPublicIcons() } func loadPublicIcons() { let request = NSFetchRequest<PublicIconImage>(entityName: "PublicIconImage") let sort = NSSortDescriptor(keyPath: \PublicIconImage.imageName, ascending: true) request.sortDescriptors = [sort] do { publicIcons = try manager.context.fetch(request) } catch let error { print("Error fetching PublicIconImages. \(error.localizedDescription)") } } } SwiftUI View struct ContentView: View { @EnvironmentObject private var publicIconViewModel: PublicIconImageViewModel var body: some View { VStack { List { ForEach(publicIconViewModel.publicIcons) { icon in HStack{ Text(icon.imageName ?? "unknown name") Spacer() if let iconImageData = icon.image, let uiImage = UIImage(data: iconImageData) { Image(uiImage: uiImage) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 35, height: 35) } } } } .onAppear { // give some time to get the images downlaoded DispatchQueue.main.asyncAfter(deadline: .now() + 5){ publicIconViewModel.loadPublicIcons() } } } .padding() } }
0
0
206
Jun ’24
SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: "group", intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, defaultValue: nil, hashModifier: nil Attribute - name: note, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: student, options: [], valueType: Optional<Student>, destination: Student, inverseName: points, inverseKeypath: Optional(\Student.points) Attribute - name: group, options: [], valueType: Array<PersistentIdentifier>, defaultValue: [], hashModifier: nil inheritedProperties: uniquenessConstraints: indices: Xcode flags this line of the macro-generated getter of the outcome property on Point: @storageRestrictions(accesses: _$backingData, initializes: _outcome) init(initialValue) { _$backingData.setValue(forKey: \.outcome, to: initialValue) _outcome = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.outcome) return self.getValue(forKey: \.outcome) // Fatal error: Failed to locate relationship for StringCodingKey... } set { _$observationRegistrar.withMutation(of: self, keyPath: \.outcome) { self.setValue(forKey: \.outcome, to: newValue) } } This worked just fine in iOS 17. Here's a snippet of the Student implementation: @Model class Student: Identifiable, Comparable { var name: String var number: Int @Relationship(deleteRule: .cascade, inverse: \Point.student) var points: [Point] @Relationship(deleteRule: .cascade, inverse: \Mark.student) var marks: [Mark] @Relationship(deleteRule: .nullify, inverse: \StudentGroup.students) var groups: [StudentGroup] = [] var archived: Bool } and the implementation of Point: @Model class Point: Identifiable, Comparable { var student: Student? var type: PointType var outcome: Outcome var proficiency: Proficiency var group: [Student.ID] = [] var date: Date var note: String } and finally the implementation for Outcome: @Model class Outcome: Identifiable, Comparable { var name: String var index: Int var rubric: Rubric? var proficiencies: [Proficiency] } I've tried adding a relationship in Outcome as an inverse of the outcomes property on Points (although this does not make sense in my implementation, which is why I initially did not set a relationship here) and the problem persisted. Any ideas what this error means and how I might go about fixing it?
0
0
219
Jun ’24