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.

Core Data Documentation

Posts under Core Data tag

358 Posts
Sort by:
Post not yet marked as solved
2 Replies
1.6k Views
I am writing a SwiftUI App using CoreData + CloudKit, based partly on sample code from `CoreDataCloudKitDemo`.There is a MasterListView which presents a List of NavigationLinks of the available data, eg. Recents, Tags, etc. embedded in a Double Column Style NavigationView.There are 6 @FetchRequest vars that collect the content for the different Sections in the List.They look similar to this:@FetchRequest(fetchRequest: ThingViewModel.fetchRequest(matching: .recent)) var recentThings:FetchedResults<Thing>Where the .fetchRequest(matching: .recent) is producing a FetchRequest with Predicate and SortDescriptors.The problems start when I use this in MultiTasking mode on an iPad. The user adds new data to the App using a Share Extension.If I have the App side by side with another App that can share to it, the share is successful, I can see the data go into CoreData and the MasterListView re-draws by the logs but the actual data is not reliably refreshed.I have logging in the MasterListView to tell me when it re-draws and when it receives a Notification from the core data stack that there has been an update.The core data stack is running a NSPersistentHistoryChangeRequest, filtering out the added Thing successfully, so I know it is there.I have tried everything I can think of, including things like: NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:) viewContext.stalenessInterval = 0 viewContext.refreshAllObjects() viewContext.stalenessInterval = -1And everything else I have found on SO ;-)What am I missing?
Posted
by
Post not yet marked as solved
7 Replies
1.7k Views
So I've been developing happily with CoreData+CloudKit for a while now, and really haven't run into any issues until this. I've migrated my model a couple of times, and it worked fine, but this was the first time I added a new entity to the model. If I run on a device (any device, iPhone, iPad, Mac via Catalyst), I get a migration error. Here's the entirety of my persistentContainer setup: public var persistentContainer: NSPersistentContainer = { let modelPath = Bundle(for: CoreDataStack.self).url(forResource: "Progress", withExtension: "momd")! let model = NSManagedObjectModel(contentsOf: modelPath)! let container = NSPersistentCloudKitContainer(name: "Progress", managedObjectModel: model) container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { print(storeDescription) fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }()And here's the error I'm getting:Callstacks=true}}}CoreData: annotation: : Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={sourceURL=[…].sqlite, reason=Cannot migrate store in-place: constraint violation during attempted migration, destinationURL=[…].sqlite, NSUnderlyingError=0x600000cebae0 {Error Domain=NSCocoaErrorDomain Code=134111 "(null)" UserInfo={_NSCoreDataOptimisticLockingFailureConflictsKey=( ), NSUnderlyingException=Constraint unique violation, reason=constraint violation during attempted migration, NSExceptionOmitCallstacks=true}}}Important note: I am not using contraints at all in this model. I have created a new Entity, given it a single attribute, and a single one-to-many relationship with an existing entity. That's all.Also, here's an excerpt from the logs when I have -com.apple.CoreData.MigrationDebug enabled, pointing to an issue with the CloudKit metadata tables update step:CoreData: annotation: Completed persistent history metadata tables update CoreData: annotation: Beginning CloudKit metadata tables update CoreData: annotation: Failed lightweight migration on connection CoreData: annotation: Rolling back formal transactionAnyone seen this, have any idea what could be failing, or how to make cloudkit/coredata happy with a migration like this?
Posted
by
Post not yet marked as solved
9 Replies
4.6k Views
Hi there! I've been messing around in Xcode 12 Beta with SwiftUI and a Core Data Model, and for some reason my ContentView preview in Xcode is failing to load. Here's the error: "Cannot preview in this file — Connection interrupted: send message to agent" I've made sure all my target memberships are synchronized, given Xcode 12 Command Line Tools in Preferences>Locations, and tried every other solution I can find out there. Any ideas?
Posted
by
Post not yet marked as solved
9 Replies
3.1k Views
Any insights on how to incorporate CloudKit (or CoreData) in the WidgetKit extension? Where in the WidgetKit api do I make the asynchronous call to load the data to be available for the TimelineProvider?
Posted
by
Post marked as solved
12 Replies
4.5k Views
On iOS 13 I used to use optional @State properties to adapt views. In my case, the presented view would either create a new object (an assignment) if the state that is passed into it is nil, or edit the assignment if an assignment was passed in. This would be done in the action block of a Button and it worked beautifully. On iOS 14 / Xcode 12 this no longer seems to work. Given the following code which creates a new assignment and passes it into the editor view when the user taps a "New Assignment" button, the value of assignment remains nil. Is anyone else experiencing similar behaviour? struct ContentView: View { 		@Environment(\.managedObjectContext) var context 		@State var assignmentEditorIsPresented = false 		@State var assignment: Assignment? = nil 		var Body: some View { 				[...] 				Button("New Assignment", action: { 						self.assignment = Assignment(context: context) 						self.assignmentEditorIsPresented = true 				}) 				.sheet(isPresented: assignmentEditorIsPresented) { 						[...] 				} 		} } What's even weirder is that I tried adding a random piece of state, an Int, to this view and modifying it right before the assignment state (between lines 9 and 10) and it didn't change either.
Posted
by
Post not yet marked as solved
1 Replies
517 Views
In development I've switched to NSPersistentCloudKitContainer and have begun the terrifying process of trying to test as many scenarios as possible to make sure nobody loses any data. During some testing I saw an error like this: <CKError 0x28033a310: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = B6015357-50E0-40B3-949F-1557F59A23DB; container ID = "iCloud.com.xxxx.yyyyyy"; partial errors: { F023EFDF-B9DE-4C17-872B-01C34C0DF129:(com.apple.coredata.cloudkit.zone:defaultOwner) = &lt;CKError 0x280266fa0: "Invalid Arguments" (12/2006); server message = "Cannot create or modify field 'CDsomeField' in record 'CDsomeRecord' in production schema"; uuid = B6015357-50E0-40B3-949F-1557F59A23DB&gt; ... 399 "Batch Request Failed" CKError's omited ... }> I was able to fix this, but it was only affecting some scenarios and if this had happened to a real user they (and I) would never have known about the problem, and their data would not have synced to CloudKit. If the store fails to load you get an error, but if it loads but doesn't sync you don't. So my question is: is there a way to receive these kind of errors in code? I have looked for notifications and delegate methods and I can't find any.
Posted
by
Post not yet marked as solved
6 Replies
2.3k Views
I'm trying to load items from the database into a list, it works fine on device and simulator but Preview will always crash with the following message: " Cannot preview in this file — Connection interrupted: send message to agent" Here's my code struct SettingsView: View {     @Environment(\.managedObjectContext) var moc     @FetchRequest(entity: ChildProfile.entity(), sortDescriptors: []) var children: FetchedResults&lt;ChildProfile&gt;          var body: some View {         VStack {             List {                 Section(header: Text("Children")) {                     ForEach(children, id: \.id) { child in                         ChildRow(child: child)                     }                 }             }         }     } } struct SettingsView_Previews: PreviewProvider {     static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)          static var previews: some View {         let defaultChild = ChildProfile(context: moc)         defaultChild.id = UUID()         defaultChild.name = "Lex"         return SettingsView().environment(\.managedObjectContext, moc)     } } Previewing ChildRow with the same preview code works fine in the canvas Is this a bug in Xcode or am I missing something?
Posted
by
Post not yet marked as solved
3 Replies
919 Views
Is the wal file supposed to fluctuate in size or just keep on growing in size? It seems to be ever-growing. data.sqlite - 266KB data.sqlite-shm - 33KB data.sqlite-wal - 3.3MB Are there any zombie objects or such causing the file size to keep on growing? How do I debug what's causing the write-ahead-log file to keep growing in size?
Posted
by
Post marked as solved
4 Replies
1k Views
I have a view that is pulling the context from the environment using the latest SwiftUI CoreData template (i.e. there is a preview/in-memory context vs the persistent context). I also have an @ObservableObject class that is fetching objects based on the predicates passed in (think dynamic filtering). A random element from these fetched results are then displayed back in the view (i.e. I do not need this ObservableObject class to be a view itself). However, there is an interesting "issue" where I cannot instantiate my @ObservedObject because the property initializers are run before "self" is available and I need to pass it the NSManagedObjectContext. The only way I can think to get around this is to create the ObservableObject class outside of the view and pass it in the view's initializer. However, this isn't completely desirable as I would prefer this data be completely private to the view as other views do not need to know about its existence. I also need it to be an ObserableObject so that the filters can change and it be reflected back in the view observing it. Am I using the wrong tool or thinking about this wrong? class Filter: ObservableObject { @Published var someObjects: [Objects] = [] /* Need to instantiate with the context so objects can be fetched */ private let context: NSManagedObjectContext } struct ContentView: View {     @Environment(\.managedObjectContext) var context &#9; /* Cannot initialize here as context isn't available */     @ObservedObject var filter = Filter(context: context) }
Posted
by
Post not yet marked as solved
8 Replies
1.1k Views
I export a small image with size of 100 kilobytes (or less) via CoreData+CloudKit. The image data is then stored in a data field in user's private database. In CloudKit dashboard, it shows that the data size is 100 kilobytes - as it should. The device's local storage increase by 100 kilobytes - as expected. However, I check the user's iCloud storage (in Settings>Apple ID>iCloud>Manage Storage). The app's storage in crease by approximately 1 megabytes. Larger by a factor of 10! I try uploading the same image to a test asset field via CloudKit Dashboard. The user's iCloud storage increase by 100 kilobytes - as expected. Why the data (bytes) field take up more of user's iCloud quota than asset field? I really prefer to directly store as data rather than as a CKAsset. Is this just the way it is... or a bug?
Posted
by
Post not yet marked as solved
1 Replies
431 Views
I'd love some help trying to understand the CoreDate template that you get when you create a new multiplatform app in Xcode 12 (beta 6 fwiw). In particular, I want to better understand what is happening in the initializer for the PersistenceController: init(inMemory: Bool = false) { container = NSPersistentContainer(name: "CoreDataTest2")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })     } In particular, I'm wondering about two things: What purpose does the inMemory Bool serve? It's set to true when the template uses the SwiftUI preview, but when else would you set it to true? When would you set it to false? When it is set to true it then creates the persistent store description to a file URL with path "/dev/null" -- what does this mean? Do we need to set the Persistent Store Description to something else in production code?
Posted
by
Post not yet marked as solved
39 Replies
1.0.0k Views
Since the release of iOS 14, I keep getting reports of this crash via Crashlytics and I have no idea how to figure out what is going wrong, because the stack trace doesn't touch my code anywhere. What can I do? How do I find the source of the problem? EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000004 Crashed: com.apple.root.user-initiated-qos 0&#9;CoreData&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b85a87ac _PFObjectIDFastHash64 + 40 1&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b254e4f8 __CFBasicHashRehash + 992 2&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b2552414 CFBasicHashRemoveValue + 2384 3&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b2469ec0 CFDictionaryRemoveValue + 236 4&#9;CoreData&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b84f51c0 -[NSManagedObjectContext(_NSInternalAdditions) _forgetObject:propagateToObjectStore:removeFromRegistry:] + 124 5&#9;CoreData&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b84d46ec -[_PFManagedObjectReferenceQueue _processReferenceQueue:] + 860 6&#9;CoreData&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x1b85a0734 -[_PFAutoreleasePoolThunk dealloc] + 48 7&#9;libobjc.A.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x1c65bb81c AutoreleasePoolPage::releaseUntil(objc_object**) + 204 8&#9;libobjc.A.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x1c65bb6e8 objc_autoreleasePoolPop + 212 9&#9;libdispatch.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x1b2120aa4 _dispatch_last_resort_autorelease_pool_pop + 44 10 libdispatch.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x1b21313c8 _dispatch_root_queue_drain + 1064 11 libdispatch.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x1b21318e8 _dispatch_worker_thread2 + 116 12 libsystem_pthread.dylib&#9;&#9;&#9;&#9;0x1f9a748cc _pthread_wqthread + 216 13 libsystem_pthread.dylib&#9;&#9;&#9;&#9;0x1f9a7b77c start_wqthread + 8
Posted
by
Post not yet marked as solved
1 Replies
688 Views
Hi, I have.a project that uses CoreData and I want to add some of the data to iCloud to sync with a Watch app and I ticked the option for the Default configuration to use iCloud and It worked but now I don't want to include images in the cloud because it became too large so I Seperated the images into a different data thing and as per instructions here https://developer.apple.com/documentation/coredata/mirroring_a_core_data_store_with_cloudkit/setting_up_core_data_with_cloudkit I added a configuration "Local" and "Cloud" and change the code as below - original lazy var persistentContainer: NSPersistentContainer = { &#9;&#9;let container = NSPersistentContainer(name: "DataModel") &#9;&#9;container.loadPersistentStores(completionHandler: { &#9;&#9;&#9;&#9;storeDescription, error in &#9;&#9;&#9;&#9;if let error = error { &#9;&#9;&#9;&#9;&#9;&#9;print("Could load data store: \(error)") &#9;&#9;&#9;&#9; } &#9;&#9;}) &#9;&#9;print("Loaded data store: DataModel") &#9;&#9;return container }() I created two configurations as per the video and ticked use with iCloud on the one I would like to sync with iCloud. new code lazy var persistentContainer: NSPersistentContainer = { &#9;&#9;var container = NSPersistentContainer(name: "DataModel") &#9;&#9;if #available(iOS 13.0, *) { &#9;&#9;&#9;&#9;container = NSPersistentCloudKitContainer(name: "DataModel") &#9;&#9;&#9;&#9;let local = NSPersistentStoreDescription(url: URL(fileURLWithPath: "/files/local.sqlite")) &#9;&#9;&#9;&#9;local.configuration = "Local" &#9;&#9;&#9;&#9;let cloud = NSPersistentStoreDescription(url: URL(fileURLWithPath: "/files/cloud.sqlite")) &#9;&#9;&#9;&#9;cloud.configuration = "Cloud" &#9;&#9;&#9;&#9;cloud.cloudKitContainerOptions = &#9;&#9;&#9;&#9;&#9;&#9;NSPersistentCloudKitContainerOptions( &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;containerIdentifier: "iCloud.com.AppName") &#9;&#9;&#9;&#9;container.persistentStoreDescriptions = [ local, cloud ] &#9;&#9;&#9;&#9;container.loadPersistentStores { storeDescription, error in &#9;&#9;&#9;&#9;&#9;&#9;guard error == nil else { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;fatalError("Could not load persistent stores. \(error!)") &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;return container &#9;&#9;} else { &#9;&#9;&#9;&#9;container.loadPersistentStores(completionHandler: { &#9;&#9;&#9;&#9;&#9;&#9;storeDescription, error in &#9;&#9;&#9;&#9;&#9;&#9;if let error = error { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;print("Could load data store: \(error)") &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;}) &#9;&#9;&#9;&#9;print("Loaded data store: DataModel") &#9;&#9;&#9;&#9;return container &#9;&#9;} }() Most of this code I got from the video https://developer.apple.com/videos/play/wwdc2019/202/ but I keep getting an error about loading or saving the persistent store or something fatal error: Could not load persistent stores. Error Domain=NSCocoaErrorDomain Code=512 "The file couldn’t be saved." UserInfo={reason=Failed to create file; code = 2}: Is anyone able to point out what I am not doing right? Thanks.
Posted
by
Post not yet marked as solved
2 Replies
1.4k Views
Greetings, I'm developing a recipe app to learn SwiftUI. It persists the user's recipe data with Core Data, recently adding CloudKit support by switching the container type to NSPersistentClouKitContainer and adding history tracking and a merge policy. Upon installation the app instantiates a persistent store with a sizable set of recipe items from a bundled JSON file, which are eventually successfully synced to iCloud. Upon installing on a *second* simulator/device, though, the JSON-supplied data is eventually duplicated in the local persistent store when an iCloud sync happens, which takes about nine minutes to occur. Two questions, then: I thought that by setting NSPersistentHistoryTrackingKey true and setting a merge policy of NSMergeByPropertyStoreTrumpMergePolicy, Core Data+Cloudkit would prevent such duplication by comparing attribute by attribute per record. The data from each installation are identical...do I have to handle duplication control manually? If so, what, then, is the point of having a merge policy? Second, why does iCloud sync consistently take nine minutes to sync the cloud-based data to the local store on the second and subsequent installations? I'd skip using the JSON-based data if that sync happened in a minute or so. Changing the size of the cloud-based data by beginning with a smaller JSON file has no effect on how long sync takes to begin trickling in data. I'm at a loss as to what the best practice is for instantiating and maintaining data on subsequent installations.
Post not yet marked as solved
3 Replies
2.7k Views
Hi all, I'm trying to figure out a proper way to list and remove/add items in a Core Data relationship. Image that a Project entity has a one-to-many relationship to Task (one-to-one inverse). When listing projects it works smoothly: ForEach(self.projects) { project in &#9; // NavigationLink to a ProjectDetailsView } So, when it goes to another View to show the selected project details, then the Core Data relationship get very weird. What's the correct way to do a ForEach on selectedProject.tasks since it's an old NSSet? not compatible with any SwiftUI component? How to add/remove items on this relationship? I tried some workaround that I found, like to extract the tasks to an array, it works fine for listing on ForEach, but when editing the items, it needs to leave the DetailsView to "reload" the updated tasks and then re-extract them again on a Array listing the correct items then. selectedProject.addToTasks(newlyCreateTask) try? self.managedObjectContext.save() It saves the Core Data entities, but do not update automatically the wrapped Array of tasks, what do not happens for project list because ForEach is watching the Core Data entities directly. I didn't find any WWDC video with this kind of example, on YouTube is full of solutions to list only, doing the Array wrapping but none for add/remove items. Cheers.
Posted
by
Post not yet marked as solved
3 Replies
1.8k Views
Hi, My middle schooler is working on a project for National Science Fair competition to estimate blood pressure from ppg signals. While he is using external database to develop his algorithm, it would be very useful to test it with real time data. I have a Series 6 watch and wondering how I can access my ppg sensor raw data.
Posted
by
Post not yet marked as solved
1 Replies
361 Views
I currently have an app that allows users to import photos, the photos are then stored in CoreData as Binary Data and then synced with iCloud. When a user wants to view the photo, I display the photo to them with Image(uiImage: UIImage(data: savedImageData)). I would like to allow users to upload live photos to the application as well, and have them saved into CoreData. I have tried searching online but haven't found a concrete process to do this. So how does one save Live Photos into CoreData? P.S. I am saving the photos from a UIImagePickerController wrapped as UIViewControllerRepresentable to input my images currently, if something else is required to get the Live Photo component as well I am open to suggestions.
Posted
by
Post not yet marked as solved
3 Replies
1.5k Views
I've been using CloudKit for my app recently and I'm trying to add support for a WatchOS app and I've enabled iCloud in capabilities and ticked the container I want to use but I get this error. CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromPartialError:forStore:inMonitor:]block_invoke(1943): <NSCloudKitMirroringDelegate: 0x282430000>: Found unknown error as part of a partial failure: <CKError 0x28112d500: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; uuid = ; container ID = "iCloud.Appname"> I tried creating a new container which worked for both the watch app and iOS app however I would like to use my original container since it has my old data
Posted
by
Post not yet marked as solved
2 Replies
615 Views
Hi Team, I've been facing a crash on iOS 14 onwards on using NSFetchedResultsController. Precondition: I'm using NSFetchRequest to initialise NSFetchedResultsController and in fetch request I'm using propertiesToFetch to fetch a single property, resultType as NSDictionaryResultType with returnsDistinctResults as YES for getting distinct results. NSFetchedResultsController is used as a data source for a table in our application. Problem: This was working fine in <iOS 14 versions, but it's started to crash for iOS 14 and and above(14.1), the reason for the same is that the dictionary we pass to get the index path in function 'indexPathForObject' is failing to return the index path with exception unrecognised selector(logs attached). I did not found any document or a new API which can be used for the same purpose. Please let me know how we can resolve this issue. Stack Trace: 2020-10-27 11:50:22.165740+0530 XYZ[70020:1505717] -[__NSSingleEntryDictionaryI objectID]: unrecognized selector sent to instance 0x600007efeb80 2020-10-27 11:50:22.245891+0530 XYZ[70020:1505717] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleEntryDictionaryI objectID]: unrecognized selector sent to instance 0x600007efeb80' First throw call stack: ( 0&#9; CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b681126 __exceptionPreprocess + 242 1&#9; libobjc.A.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x000000010b511f78 objc_exception_throw + 48 2&#9; CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b68fc6f +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0 3&#9; CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b685666 _forwarding_ + 1489 4&#9; CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b687698 _CF_forwarding_prep_0 + 120 5&#9; CoreData&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x00000001051e3f23 -[_NSDefaultSectionInfo indexOfObject:] + 80 6&#9; CoreData&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010533671d -[NSFetchedResultsController indexPathForObject:] + 151 7&#9; Lido_mPilot&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000101ed4ac3 -[LMSFetchedResultsDataSource indexPathForObject:] + 99 8&#9; Lido_mPilot&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x000000010238b1dc -[LMSFleetTableViewDataSource indexPathForObject:] + 140 9&#9; Lido_mPilot&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000101e160ad -[LMSFleetTableViewController viewWillAppear:] + 365 10&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000122115fb2 -[UIViewController _setViewAppearState:isAnimating:] + 654 11&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x00000001221167db -[UIViewController __viewWillAppear:] + 106 12&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000122047534 -[UINavigationController _startTransition:fromViewController:toViewController:] + 726 13&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000122048371 -[UINavigationController _startDeferredTransitionIfNeeded:] + 851 14&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x00000001220496dc -[UINavigationController __viewWillLayoutSubviews] + 150 15&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000122029f1e -[UILayoutContainerView layoutSubviews] + 217 16&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000122d9c9ce -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2874 17&#9;QuartzCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x00000001099e9d87 -[CALayer layoutSublayers] + 258 18&#9;QuartzCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x00000001099f0239 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 575 19&#9;QuartzCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x00000001099fbf91 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 65 20&#9;QuartzCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010993c078 _ZN2CA7Context18commit_transactionEPNS_11TransactionEdPd + 496 21&#9;QuartzCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x0000000109972e13 _ZN2CA11Transaction6commitEv + 783 22&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x00000001228701a3 _afterCACommitHandler + 164 23&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b5ee6b3 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 24&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b5e8f3f __CFRunLoopDoObservers + 547 25&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b5e94e2 __CFRunLoopRun + 1113 26&#9;CoreFoundation&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010b5e8b9e CFRunLoopRunSpecific + 567 27&#9;GraphicsServices&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;0x000000010e2e3db3 GSEventRunModal + 139 28&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x000000012283faf3 -[UIApplication _run] + 912 29&#9;UIKitCore&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000122844a04 UIApplicationMain + 101 30&#9;Lido_mPilot&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x0000000102421ce1 main + 193 31&#9;libdyld.dylib&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; 0x000000010cf64415 start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleEntryDictionaryI objectID]: unrecognized selector sent to instance 0x600007efeb80' terminating with uncaught exception of type NSException CoreSimulator 732.17 - Device: iPad Pro (9.7-inch) (FE6E057B-B3C6-495D-9305-182325E6C237) - Runtime: iOS 14.0 (18A372) - DeviceType: iPad Pro (9.7-inch) Thank You Harish Pathak
Posted
by
Post marked as solved
3 Replies
954 Views
The app uses Core Data + CloudKit. When the app gets launched WidgetKit file fetches correct entries from Core Data but when I add new entries to Core Data from the main app and call WidgetCenter.shared.reloadTimelines() updated entries don't get fetched and old data is displayed inside the widget. Main app and Widget target have the same App group, iCloud capability enabled for both targets. When I call WidgetCenter.shared.reloadTimelines() from the Main app Widget reloads (timer added to Widget view sets to zero) but fetch from Core Data doesn't return newly added entries. Then I restart the app and correct entries get fetched. Why doesn't it fetch correct entries when WidgetCenter.shared.reloadTimelines() gets called and only works when app is relaunched? Widget's code: import WidgetKit import SwiftUI import CoreData struct Provider: TimelineProvider { &#9;&#9;func placeholder(in context: Context) -> HabitsEntry { &#9;&#9;&#9;&#9;HabitsEntry(date: Date(), habitsCount: 0) &#9;&#9;} &#9;&#9;func getSnapshot(in context: Context, completion: @escaping (HabitsEntry) -> ()) { &#9;&#9;&#9;&#9;let entry = HabitsEntry(date: Date(), habitsCount: 0) &#9;&#9;&#9;&#9;completion(entry) &#9;&#9;} &#9;&#9;func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;let managedObjectContext = Storage.viewContext &#9;&#9;&#9;&#9;let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DailyHabit") &#9;&#9;&#9;&#9;let predicate = Storage.getCurrentDatePredicate() &#9;&#9;&#9;&#9;request.predicate = predicate &#9;&#9;&#9;&#9;var habits = 0 &#9;&#9;&#9;&#9;do { habits = try managedObjectContext.count(for: request)&#9;} &#9;&#9;&#9;&#9;catch let error as NSError {print ("Could not fetch \(error), \(error.userInfo)")} &#9;&#9;&#9;&#9;let entry = [HabitsEntry(date: Date(), habitsCount: habits)] &#9;&#9;&#9;&#9;let timeline = Timeline(entries: entry, policy: .never) &#9;&#9;&#9;&#9;completion(timeline) &#9;&#9;} } struct HabitsEntry: TimelineEntry { &#9;&#9;let date: Date &#9;&#9;var habitsCount: Int } struct HabitsHomeWidgetEntryView : View { &#9;&#9;var entry: Provider.Entry &#9;&#9;var body: some View { &#9;&#9;&#9;Text(entry.date, style: .timer) &#9;&#9;&#9;Text("There are \(entry.habitsCount) daily habits") &#9;&#9;} } @main struct HabitsHomeWidget: Widget { &#9;&#9;let kind: String = "HabitsHomeWidget" &#9;&#9;var body: some WidgetConfiguration { &#9;&#9;&#9;&#9;StaticConfiguration(kind: kind, provider: Provider()) { entry in &#9;&#9;&#9;&#9;&#9;&#9;HabitsHomeWidgetEntryView(entry: entry) &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;.configurationDisplayName("My Widget") &#9;&#9;&#9;&#9;.description("This is an example widget.") &#9;&#9;} }&#9; Here is the code for Core Data: import UIKit import CoreData import WidgetKit class Storage { &#9; &#9;static let shared = Storage() &#9; &#9;static var persistentContainer: NSPersistentContainer { &#9;&#9;return Storage.shared.persistentContainer &#9;} &#9; &#9;static var viewContext: NSManagedObjectContext { &#9;&#9;return persistentContainer.viewContext &#9;} &#9; &#9;lazy var persistentContainer: NSPersistentContainer = { &#9;&#9;let container: NSPersistentContainer &#9;&#9; &#9;&#9;let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.appGroupName)! &#9;&#9;let storeURL = containerURL.appendingPathComponent("NoRegrets.sqlite") &#9;&#9;let description = NSPersistentStoreDescription(url: storeURL) &#9;&#9;if isICloudContainerAvailable { &#9;&#9;&#9;container = NSPersistentCloudKitContainer(name: Constants.persistentContainerName) &#9;&#9;} else { &#9;&#9;&#9;container = NSPersistentContainer(name: Constants.persistentContainerName) &#9;&#9;} &#9;&#9;description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) &#9;&#9;description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) &#9;&#9;description.shouldMigrateStoreAutomatically = true &#9;&#9;description.shouldInferMappingModelAutomatically = true &#9;&#9;let storeDescription = description &#9;&#9; &#9;&#9;container.persistentStoreDescriptions = [storeDescription] &#9;&#9; &#9;&#9;container.loadPersistentStores(completionHandler: { (storeDescription, error) in &#9;&#9;&#9;if let error = error as NSError? { &#9;&#9;&#9;&#9;return &#9;&#9;&#9;} &#9;&#9;}) &#9;&#9; &#9;&#9;container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy &#9;&#9;container.viewContext.automaticallyMergesChangesFromParent = true &#9;&#9; &#9;&#9;do { &#9;&#9;&#9;try container.viewContext.setQueryGenerationFrom(.current) &#9;&#9;} catch { &#9;&#9;&#9;print("Failed to pin viewContext to the current generation: \(error)") &#9;&#9;} &#9;&#9;return container &#9;}() &#9; &#9;var isICloudContainerAvailable: Bool { &#9;&#9;FileManager.default.ubiquityIdentityToken != nil &#9;} &#9; &#9;// MARK: - Core Data Saving support &#9;func saveContext() { &#9;&#9;let context = persistentContainer.viewContext &#9;&#9;if context.hasChanges { &#9;&#9;&#9;do { &#9;&#9;&#9;&#9;try context.save() &#9;&#9;&#9;&#9; &#9;&#9;&#9;} catch { &#9;&#9;&#9;&#9;let nserror = error as NSError &#9;&#9;&#9;&#9;print("Saving error: \(nserror)") &#9;&#9;&#9;} &#9;&#9;} &#9;} } // MARK: - Helper methods extension Storage { &#9;func getCurrentUser() -> User? { &#9;&#9;let fetchRequest = User.createFetchRequest() &#9;&#9;fetchRequest.fetchLimit = 1 &#9;&#9;fetchRequest.sortDescriptors = [NSSortDescriptor(key: "objectID", ascending: false)] &#9;&#9; &#9;&#9;let user = try? Storage.viewContext.fetch(fetchRequest).first &#9;&#9;return user &#9;} &#9; &#9;class func getCurrentDatePredicate() -> NSPredicate { &#9;&#9;var calendar = Calendar.current &#9;&#9;calendar.timeZone = NSTimeZone.local &#9;&#9;let dateFrom = calendar.startOfDay(for: Date()) &#9;&#9;let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom) &#9;&#9;let fromPredicate = NSPredicate(format: "date >= %@", dateFrom as NSDate) &#9;&#9;let toPredicate = NSPredicate(format: "date < %@", dateTo! as NSDate) &#9;&#9;return NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate]) &#9;} }
Posted
by