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

CoreData CloudKit sync resulting in main thread initialisation issue
I'm using Xcode 14 beta 4, on macOS Monterey 12.5, developing a Mac app that's using CoreData CloudKit sync — with my context being configured with two configurations (one for a local cache and one data synced via CloudKit). An issue recently appeared where the app crashes soon after start-up with this message: [threadmgrsupport] _TSGetMainThread_block_invoke:Main thread potentially initialized incorrectly, cf <rdar://problem/67741850> And this stack trace: Thread 1 Queue : com.apple.main-thread (serial) #0 0x000000018b86b5e8 in ___NSAssertMainEventQueueIsCurrentEventQueue_block_invoke () #1 0x0000000105b563a8 in _dispatch_client_callout () #2 0x0000000105b58300 in _dispatch_once_callout () #3 0x000000018b86a2dc in _DPSNextEvent () #4 0x000000018b868e14 in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] () #5 0x000000018b85afe0 in -[NSApplication run] () #6 0x000000018b82c6fc in NSApplicationMain () #7 0x00000001ae281e98 in specialized runApp(_:) () #8 0x00000001aee10588 in runApp<τ_0_0>(_:) () #9 0x00000001ae88626c in static App.main() () Things work again, if I disable the CloudKit sync by not setting cloudKitContainerOptions on my "Cloud" configuration. Similarly, it works on first install, but reappears on subsequent runs. The code is in a package that's shared with an iOS version of the app, which has no such issues. I also tried going back to previous commits that worked before, and it works again until at some point it stops working again for the same commits. So it doesn't seem to be caused directly by my code, but rather by something that the CloudKit sync is doing. Any help would be much appreciated.
3
2
2.0k
Oct ’23
NSCocoaErrorDomain code = 134093 , only in iOS16
i have received a lot of crash log only in iOS16 the crash occured when i called : [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:resultHandler] here is the crash log Exception Type: NSInternalInconsistencyException ExtraInfo: Code Type: arm64 OS Version: iPhone OS 16.0 (20A5328h) Hardware Model: iPhone14,3 Launch Time: 2022-07-30 18:43:25 Date/Time: 2022-07-30 18:49:17 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:Unhandled error (NSCocoaErrorDomain, 134093) occurred during faulting and was thrown: Error Domain=NSCocoaErrorDomain Code=134093 "(null)" Last Exception Backtrace: 0 CoreFoundation 0x00000001cf985dc4 0x1cf97c000 + 40388 1 libobjc.A.dylib 0x00000001c8ddfa68 0x1c8dc8000 + 96872 2 CoreData 0x00000001d56d2358 0x1d56cc000 + 25432 3 CoreData 0x00000001d56fa19c 0x1d56cc000 + 188828 4 CoreData 0x00000001d5755be4 0x1d56cc000 + 564196 5 CoreData 0x00000001d57b0508 0x1d56cc000 + 935176 6 PhotoLibraryServices 0x00000001df1783e0 0x1df0ed000 + 570336 7 Photos 0x00000001df8aa88c 0x1df85d000 + 317580 8 PhotoLibraryServices 0x00000001df291de0 0x1df0ed000 + 1723872 9 CoreData 0x00000001d574e518 0x1d56cc000 + 533784 10 libdispatch.dylib 0x00000001d51fc0fc 0x1d51f8000 + 16636 11 libdispatch.dylib 0x00000001d520b634 0x1d51f8000 + 79412 12 CoreData 0x00000001d574e0a0 0x1d56cc000 + 532640 13 PhotoLibraryServices 0x00000001df291d94 0x1df0ed000 + 1723796 14 PhotoLibraryServices 0x00000001df291434 0x1df0ed000 + 1721396 15 Photos 0x00000001df8a8380 0x1df85d000 + 308096 16 Photos 0x00000001df89d050 0x1df85d000 + 262224 17 Photos 0x00000001df87f62c 0x1df85d000 + 140844 18 Photos 0x00000001df87ee94 0x1df85d000 + 138900 19 Photos 0x00000001df87e594 0x1df85d000 + 136596 20 Photos 0x00000001df86b5c8 0x1df85d000 + 58824 21 Photos 0x00000001df86d938 0x1df85d000 + 67896 22 Photos 0x00000001dfa37a64 0x1df85d000 + 1944164 23 Photos 0x00000001dfa37d18 0x1df85d000 + 1944856 24 youavideo -[YouaImageManager requestImageDataForAsset:options:resultHandler:] (in youavideo) (YouaImageManager.m:0) 27 25 youavideo -[YouaAlbumTransDataController requstTransImageHandler:] (in youavideo) (YouaAlbumTransDataController.m:0) 27 26 youavideo -[YouaAlbumTransDataController requstTransWithHandler:] (in youavideo) (YouaAlbumTransDataController.m:77) 11 27 youavideo -[YouaUploadTransDataOperation startTrans] (in youavideo) (YouaUploadTransDataOperation.m:102) 19 28 Foundation 0x00000001c9e78038 0x1c9e3c000 + 245816 29 Foundation 0x00000001c9e7d704 0x1c9e3c000 + 268036 30 libdispatch.dylib 0x00000001d51fa5d4 0x1d51f8000 + 9684 31 libdispatch.dylib 0x00000001d51fc0fc 0x1d51f8000 + 16636 32 libdispatch.dylib 0x00000001d51ff58c 0x1d51f8000 + 30092 33 libdispatch.dylib 0x00000001d51febf4 0x1d51f8000 + 27636 34 libdispatch.dylib 0x00000001d520db2c 0x1d51f8000 + 88876 35 libdispatch.dylib 0x00000001d520e338 0x1d51f8000 + 90936 36 libsystem_pthread.dylib 0x00000002544b9dbc 0x2544b9000 + 3516 37 libsystem_pthread.dylib 0x00000002544b9b98 0x2544b9000 + 2968 i can't find the error code 134093 definition i don't know what's going wrong in iOS16 Would anyone have a hint of why this could happen and how to resolve it? thanks very much
7
5
2.8k
Jun ’24
Swift Concurrency, Core Data, "partially thread-safe" types & Sendable conformance
Hi, Xcode warns me that NSPersistentContainer, NSManagedObjectContext, NSPersistentHistoryTransaction and NSPersistentHistoryToken are non-Sendable types and therefore cannot cross actor boundaries. These warnings occur even when I use @preconcurrency import CoreData (only works with Xcode 14.0 Beta, in Xcode 13.4.1, it says '@preconcurrency' attribute on module 'CoreData' is unused) I understand that types in Core Data have yet to be marked as Sendable when it makes sense. Although NSPersistentHistoryTransaction, and NSPersistentHistoryToken are reference types, they should qualify to be marked as Sendable in the future since these are immutable types, am I right? NSPersistentContainer provides variables and methods like viewContext and newBackgroundContext(). It would make sense that this type is thread-safe. However, I'm not sure about it, especially regarding its loadPersistentStores(completionHandler:) method. Is NSPersistentContainer (and its subclass NSPersistentCloudKitContainer) thread-safe and should it be marked as Sendable in the future? The case of and NSManagedObjectContext confuses me the most. Indeed, it has both thread-safe methods like perform(_:) and thread-unsafe methods like save(). Still, it should be possible to cross actor boundaries. Would such a "partially thread-safe" type quality to be marked as Sendable? If not, how can it cross actor boundaries? The reason I'm asking these questions is that I have a CoreDataStack type. It has mutable variables, such as var lastHistoryToken: NSPersistentHistoryToken?, needs to perform work without blocking the main thread, such as writing the token to a file, has async methods, uses notification observers, and needs to be marked as Sendable to be used by other controllers running on different actors. Since this type is related to back-end work, I made it an Actor. This type exposes the persistent container, and a method to create new background threads. However, I need to explicitly annotate all methods using await context.perform { ... } as nonisolated in this actor. Not doing so causes a data race to be detected at runtime. Is this a bug, and is making a Core Data stack an Actor the proper way to do it or is there a better solution? Any help would be greatly appreciated. Thanks. Xcode Configuration Xcode 13.4.1, Xcode 14.0 beta 5 The Xcode project is configured with Other Swift Flags set to -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks.
4
2
2.6k
Oct ’23
Not receiving Persistent Store Remote Change Notification.
Before the code... CloudKit, background mode (remote notifications) and push notifications are added to Capabilities. Background sync is working fine and view loads current store on manual fetch. Code that initialises the persistent container in app delegate... - (NSPersistentCloudKitContainer *)persistentContainer {     // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.     @synchronized (self) {         if (_persistentContainer == nil) {             _persistentContainer = [[NSPersistentCloudKitContainer alloc] initWithName:@"Expenses"];             [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {                 if (error != nil) {                     __block NSPersistentStoreDescription *sDescription = storeDescription;                     dispatch_async(dispatch_get_main_queue(), ^(){                         [sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"PersistentHistoryTracking"];                         [sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"NSPersistentStoreRemoteChangeNotificationOptionKey"];                     }); #ifdef DEBUG                     NSLog(@"Unresolved error %@, %@", error, error.userInfo); #endif                     abort();                 }                 else #ifdef DEBUG                     NSLog(@"Store successfully initialized"); #endif             }];         }     }     return _persistentContainer; } In Home view controller which is the initial view controller i am adding an observer for the remote notification...     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadViewONCKChangeNotification) name:NSPersistentStoreRemoteChangeNotification object:[appDelegate.persistentContainer persistentStoreCoordinator]]; I am not receiving any store change notifications. Have added breakpoints to see if selector is fired. no go. CloudKit Console also doesn't show any pushes for the concerned time period.
4
0
1.2k
Jan ’24
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.1k
3d
"Failed to set up CloudKit integration" in TestFlight build
I'm building a macOS + iOS SwiftUI app using Xcode 14.1b3 on a Mac running macOS 13.b11. The app uses Core Data + CloudKit. With development builds, CloudKit integration works on the Mac app and the iOS app. Existing records are fetched from iCloud, and new records are uploaded to iCloud. Everybody's happy. With TestFlight builds, the iOS app has no problems. But CloudKit integration isn't working in the Mac app at all. No existing records are fetched, no new records are uploaded. In the Console, I see this message: error: CoreData+CloudKit: Failed to set up CloudKit integration for store: <NSSQLCore: 0x1324079e0> (URL: <local file url>) Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction.} I thought it might be that I was missing the com.apple.security.network.client entitlement, but adding that didn't help. Any suggestions what I might be missing? (It's my first sandboxed Mac app, so it might be really obvious to anyone but me.)
2
0
2.1k
Oct ’23
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
5.9k
2d
Swift UI Preview for Multiple Entity
Hello, I've created multiple Entity in CoreData, that has a relationship to one another. However, I'm unable to create @discardableResult to use in SwiftUI preview. /// Entity data for use with canvas previews. static var preview: Entity1 {         let entities1 = Entity1.makePreviews(count: 1)         return entities1[0] } @discardableResult static func makePreviews(count: Int) -&gt; [Entity1] {         var contents = [Entity1]()         let viewContext = PersistenceController.preview.container.viewContext         let persistenceController = PersistenceController.shared         for index in 0..&lt;count {             let entities1 = Entity1(context: viewContext)             entities1.id = UUID()             entities1.title = "Amazing day!"             let photo = Photo(context: viewContext)             let imageData = UIImage(named: "Golden Temple")?.jpegData(compressionQuality: 1) ?? Data()             photo.linkedToJournal = journal             let thumbnail = Thumbnail(context: viewContext)             let thumbnailData = persistenceController.thumbnail(with: imageData)?.jpegData(compressionQuality: 1)             thumbnail.data = thumbnailData             thumbnail.photo = photo             let photoDataObject = PhotoData(context: viewContext)             photoDataObject.data = imageData             photoDataObject.photo = photo             contents.append(entities1)         }         return contents } You may also try to use the sample code from https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users to build a SwiftUI Preview. Appreciate if you could suggest how to build a SwiftUI preview as it saves a lot of development effort and time. Thank you very much!
1
0
962
Nov ’23
Unable to load CloudKit CoreData Store
I have a CoreData model, in a Swift Package with tests. I can successfully run the tests, when I load the model using NSPersistentContainer, however attempting this with NSPersistentCloudKitContainer always fails in the call to loadPersistentStores(completionHandler block: @escaping (NSPersistentStoreDescription, Error?) -> Void) The error is : [CK] BUG IN CLIENT OF CLOUDKIT: Not entitled to listen to push notifications. Please add the 'aps-connection-initiate' entitlement. This issue is described on StackOverflow however, the accepted solution does not appear to work in my case. I have tried adding the aps-connection-initiate key to my App Info.plist, the Test Info.plist and the SPM bundle. No change. (NB. adding this to the entitlements file just breaks auto signing). I have enabled App entitlements for App Groups, Remote Notifications background mode, Push Notifications and iCloud CloudKit with a store identifier. I have checked my model. All relationships have inverses. No unique constraints, etc. etc. I am sharing a Bundle ID with a previous version of the App, that also uses CoreData+CloudKit, each version has it's own Model and container identifier, each container identifier is available in the provisioning profile. The new version of the model has two NSPersistentStoreDescriptions, one is configured for CloudKit, the other is a local cache. I am completely stuck, suggestions would be very welcome.
3
1
1.4k
May ’24
Core data failed to find the migration mapping file due to the derived attribute.
Hi, I have found another bug if I'm not mistaken in core data. When we are using a derived attribute in our xcdatamodel file after making the mapping file there is an error: Can't find mapping model for migration If you are looking to reproduce the bug I made a super simple example app at my branch in the link below: https://github.com/hamed8080/LeitnerBox/tree/fix_migration Keep that in mind if I remove the derived attribute and afterward make a migration with a new mapping file, it works correctly!
1
0
581
Oct ’23
Update Watch Complication with CloudKit
I have an iPhone app the uses CloudKit for Core Data syncing. I also have a companion Apple Watch app that syncs to the same CloudKit records. The watch can be used without the iPhone app as well but they both independently sync to the same CloudKit database. This works reasonably well. As soon as either app is opened, the CloudKit will pull down the latest records. I'd like to add a watch complication that shows the state of the CloudKit records. I supported this by adding a Widget extension, embedded in my watch app. The Core Data database in the watch app is part of an app group, so the complication is able to query the same database. So far so good. I'm running into problems with the complication updating after remote records are changed from the iPhone. Here is what is happening: When records are changed on the iPhone, the data syncs to CloudKit but the watch app is not updated when in the background. This is noticed when you open the app and it takes a second for the view to show the new records. Since Core Data database on the watch is not being updated while in the background, the complication is not being updated at all. Part of my confusion is I assumed CloudKit was meant to make this more seamless with silent push notifications? I have the "Remote Notifications" capability enabled on my WatchApp. It seems that only works while the app is in the foreground though. This seems very limiting when you have a complication that depends on the Watch app's Core Data state. I have a few things to work around this with mixed success: "Wake" the watch app explicitly when records are changed on the iPhone app using WatchConnectivityManager. The hope is that by waking the watch app, it will sync with iCloud. This either isn't working or intermittenly works. It is also not clear to me that by activating the watch app, that it will trigger records to sync. I wish there were a way to ask Core Data to sync explicitly. Whenever the Apple watch app wakes in the last step, ask it to WidgetCenter to reload the widget. This process feels convoluted and seems to negate some of the the benefits of CloudKit to synchronize data which I thought would be baked into this process. Any thoughts on a better approach to all this?
3
1
1.2k
Sep ’23
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.7k
5d
iOS 16.4 - UICollectionView and NSFetchedResultsController
Since iOS 16.4, a new exception is raised when "the number of sections and/or items returned by the data source before and/or after performing the batch updates are inconsistent with the updates". This post (iOS 16.4.1 - UICollectionViewController crashes) goes into some more detail, with a response from an Apple engineer, but doesn't explain exactly how this mechanism should/could work with NSFetchedResultsController. When using NSFetchedResultsController, its contents could contain unfetched/faulted core data objects in the tens of thousands. As the NSArray returned by NSFetchedResultsController is a reference type, the developer has no control over the point in time it is updated. Further, there doesn't seem to be a way to copy NSFetchedResultsSectionInfo without triggering a deep copy. Therefore, if a developer wishes to play nicely with the UICollectionView batch updates mechanism they are forced to make a deep copy of the results which means faulting a bunch of potentially unused objects and defeating a primary benefit of NSFetchedResultsController. Is there a more performance optimised way of getting UICollectionView batch updates and NSFetchedResultsController to play nicely?
3
0
923
Oct ’23
Can a private database entity have a relationship to a public database entity?
I’m using NSPersistentCloudKitContainer and I’m utilising the public database and also the user’s private database. For example I have an entity called Category which has a many-to-many relationship to an entity called NewsArticle. So the NewsArticles exist in the public database for the user to browse, but he can add them to a category which will live in his private database. So that’s my question, is it possible for an entity which exists a in the private database to have a relationship to another entity in a public database?
1
1
601
May ’24
Access Core Data ModelContainer with SwiftData
I have an app that uses CoreData and I want to migrate to SwiftData. After following the Migrate to SwiftData session, I only need to point to my old Core Data file to read the old data and convert it to the new SwiftData format. My question is how do I do this? Maybe worth mentioning is that my NSPersistentContainer(name: "Model") is different to my app name. Possible Solution? According to a Tweet by Donny Wals this is done this way: By default a SwiftData ModelContainer will create its underlying storage in a file called default.store. If you want to change this so you can use an existing Core Data SQLite file, you can point your container to that file instead: // point to your old sqlite file let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) modelContainer = try ModelContainer(for: [ Movie.self ], config) My Tested Code @main struct SwiftData_TestApp: App { let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) let modelContainer = try ModelContainer(for: [ Item.self ], config) var body: some Scene { WindowGroup { ContentView() } .modelContainer(modelContainer) } } The problem here is that I don’t get it to work in the main app struct. When using this the way described in Dive deeper into SwiftData (at 6:58) I only get the error: Cannot use instance member 'url' within property initializer; property initializers run before 'self' is available PS: There seems to be an issue with this WWDC session method anyway – see this post.
2
0
1.9k
May ’24
Weird Coredata error
Hi I really don't understand. I have a record type on CloudKit where I store some data and a corresponding entity on core data that I sync with CloudKit with a very basic routine at some point I call this func: func GetUserFromCoredata(userID:String)->UserEntity? { var fetched:[UserEntity]?=nil let fetch = NSFetchRequest<UserEntity>(entityName:"UserEntity") let predicate = NSPredicate(format:"TRUEPREDICATE") fetch.predicate = predicate fetch.affectedStores = [DBGlobals.localStore, DBGlobals.cloudStore] do{ print("RICHIESTA FETCH UTENTI IN COREDATA") fetched = try context.fetch(fetch) } catch{ fatalError("errore nel recupero dell'elenco utenti") } if let found = fetched { for el in found { if el.userID == userID { return el } } } return nil } As you can see nothing special. it is only a fetch made on two stores. If I run the code 20 times 19 are good and 1 result in a fatal error with this text: 2023-06-28 17:56:49.684780+0200 xDeskApp[23313:2379150] -[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x215632f50 2023-06-28 17:56:49.712724+0200 xDeskApp[23313:2379150] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x283d88000> , -[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x215632f50 with userInfo of (null) 2023-06-28 17:56:49.974635+0200 xDeskApp[23313:2379150] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x215632f50' *** First throw call stack: (0x1bd4d4cb4 0x1b657c3d0 0x1bd649ab8 0x1bd4eb0e8 0x1bd551900 0x1c4c53594 0x1c4bdf848 0x1c4bdf4b0 0x1c4c81d80 0x1068fa038 0x10690b814 0x1c4c81c20 0x1c4bcef68 0x1c4bcee38 0x1c4bbe200 0x1c4bc9a78 0x1c4d3752c 0x1c4c02678 0x1c4bc86d8 0x1c4bbb9fc 0x1c4bb6b14 0x1c4cc97ec 0x104bf00b0 0x104bef860 0x104bee8f4 0x1c4f82ce8 0x1c4f82d8c 0x1c5068cac 0x1c4f1f3b0 0x1c4f11338 0x1c50689d4 0x1bd53dc04 0x1bd4ebcb4 0x1bd4eb6cc 0x1c4fcc800 0x10690b158 0x1068fa038 0x1069020b0 0x106902e28 0x10690fc74 0x21d250ddc 0x21d250b7c) libc++abi: terminating due to uncaught exception of type NSException (Recorded stack frame) ... and really, I can't understand. the predicate is absolutely basic, the entity exist, here I am not syncing anything, just fetching the records in the two stores... what am I doing wrong? why 19 su 20 are good and one is catching this error?
2
0
708
Sep ’23
Fatal crash when using CoreData and deleting item from list with Section headers
Greetings - The following code appears to work, but when a list item is deleted from a Category section that contains other list items, the app crashes (error = "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x180965354)"). I've confirmed that the intended item is deleted from the appData.items array - the crash appears to happen right after the item is deleted. I suspect that the problem somehow involves the fact that the AppData groupedByCategory dictionary and sortedByCategory array are computed properties and perhaps not updating as intended when an item is deleted? Or maybe the ContentView doesn't know they've been updated? My attempt to solve this by adding "appData.objectWillChange.send()" has not been successful, nor has my online search for solutions to this problem. I'm hoping someone here will either know what's happening or know I could look for additional solutions to try. My apologies for all of the code - I wanted to include the three files most likely to be the source of the problem. Length restrictions prevent me from including the "AddNewView" code and some other details, but just say the word if that detail would be helpful. Many, many thanks for any help anyone can provide! @main struct DeletionCrashApp: App { let persistenceController = PersistenceController.shared // Not sure where I should perform this command @StateObject var appData = AppData(viewContext: PersistenceController.shared.container.viewContext) var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) .environmentObject(appData) } } } import Foundation import SwiftUI import CoreData class AppData: NSObject, ObservableObject { // MARK: - Properties @Published var items: [Item] = [] private var fetchedResultsController: NSFetchedResultsController<Item> private (set) var viewContext: NSManagedObjectContext // viewContext can be read but not set from outside this class // Create a dictionary based upon the category var groupedByCategory: [String: [Item]] { Dictionary(grouping: items.sorted(), by: {$0.category}) } // Sort the category-based dictionary alphabetically var sortedByCategoryHeaders: [String] { groupedByCategory.map({ $0.key }).sorted(by: {$0 < $1}) } // MARK: - Methods func deleteItem(itemObjectID: NSManagedObjectID) { do { guard let itemToDelete = try viewContext.existingObject(with: itemObjectID) as? Item else { return // exit the code without continuing or throwing an error } viewContext.delete(itemToDelete) } catch { print("Problem in the first do-catch code: \(error)") } do { try viewContext.save() } catch { print("Failure to save context: \(error)") } } // MARK: - Life Cycle init(viewContext: NSManagedObjectContext) { self.viewContext = viewContext let request = NSFetchRequest<Item>(entityName: "ItemEntity") request.sortDescriptors = [NSSortDescriptor(keyPath: \Item.name, ascending: true)] fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: viewContext, sectionNameKeyPath: nil, cacheName: nil) super.init() fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() guard let items = fetchedResultsController.fetchedObjects else { return } self.items = items } catch { print("failed to fetch items: \(error)") } } // end of init() } // End of AppData extension AppData: NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { guard let items = controller.fetchedObjects as? [Item] else { return } self.items = items } } import SwiftUI import CoreData struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @EnvironmentObject var appData: AppData @State private var showingAddNewView = false @State private var itemToDelete: Item? @State private var itemToDeleteObjectID: NSManagedObjectID? var body: some View { NavigationView { List { ForEach(appData.sortedByCategoryHeaders, id: \.self) { categoryHeader in Section(header: Text(categoryHeader)) { ForEach(appData.groupedByCategory[categoryHeader] ?? []) { item in Text(item.name) .swipeActions(allowsFullSwipe: false) { Button(role: .destructive) { self.itemToDelete = appData.items.first(where: {$0.id == item.id}) self.itemToDeleteObjectID = itemToDelete!.objectID appData.deleteItem(itemObjectID: itemToDeleteObjectID!) // appData.objectWillChange.send() <- does NOT fix the fatal crash } label: { Label("Delete", systemImage: "trash.fill") } } // End of .swipeActions() } // End of ForEach(appData.groupedByReplacementCategory[categoryHeader] } // End of Section(header: Text(categoryHeader) } // End of ForEach(appData.sortedByCategoryHeaders, id: \.self) } // End of List .navigationBarTitle("", displayMode: .inline) .navigationBarItems( trailing: Button(action: { self.showingAddNewView = true }) { Image(systemName: "plus") } ) .sheet(isPresented: $showingAddNewView) { // show AddNewView here AddNewView(name: "") } } // End of NavigationView } // End of body } // End of ContentView extension Item { @nonobjc public class func fetchRequest() -> NSFetchRequest<Item> { return NSFetchRequest<Item>(entityName: "ItemEntity") } @NSManaged public var category: String @NSManaged public var id: UUID @NSManaged public var name: String } extension Item : Identifiable { }
3
1
1k
Feb ’24
iOS 17 BUG IN CLIENT OF CLOUDKIT: Not entitled to listen to push notifications.
I have a SwiftUI app that uses Core Data and CloudKit. Using the Xcode 15 beta and iOS17 beta simulator, some of the runs cause the app to crash on startup. The console prints the following: BUG IN CLIENT OF CLOUDKIT: Not entitled to listen to push notifications. Please add the 'aps-connection-initiate' entitlement. Push notifications are added correctly and everything works on iOS16 and earlier. This crash also only occurs in about 20% runs on iOS17 beta. Any tips on how to resolve this?
1
0
632
Jul ’23
Migration Questions CoreData to SwiftData
Hi, I am looking to migrate a CoreData app which uses CloudKit to SwiftData and have two (for now) migration questions. (1) Many of the attributes have the Optional checkbox checked in the xcdatamodeld file. The corresponding SwiftData properties are marked as Optional (?) but are never not initialized to an actual value. Can I remove the ? from those property types or am I required to do this as a migration? (1a) If I'm required to do this as a migration, is this a custom migration or can I do it as a light migration. (2) I have several Int16 in the Core Data model which I'd like to make Ints in the SwiftData model. Is this a migration? Is it a custom one or can the migration make the conversion. Thank you, Daniel
1
0
888
Jul ’23
The model configuration used to open the store is incompatible with the one that was used to create the store.
I have deleted the app and try to run the Xcode project again. How can I remove this error ? Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store." UserInfo={NSAffectedObjectsErrorKey=<NSManagedObject: 0x6000021c5310>
2
1
1.2k
Oct ’23