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

iOS NSCoreDataCoreSpotlightDelegate, how to reindex all items
I have implemented NSCoreDataCoreSpotlightDelegate, and I missed out the part where the default expirationDate is 1 month, now items that I have added 3 months ago are not showing up in the search index.How do I get NSCoreDataCoreSpotlightDelegate to reindex all the items?I used to be able to call this:mcdcsd.searchableIndex(CSSearchableIndex.default(), reindexAllSearchableItemsWithAcknowledgementHandler: {})And the first time, it will reindex all the items, but if I re-run the app with the above line uncommented again, it will not reindex.If I uninstall the app, install back, then uncomment the above line, then it will index all again for the first time.How do I get it to reindex everything again?
2
0
1.7k
Nov ’23
CD4CK: Can't find Default configuration in M.O.M.
There are a few things about how Core Data 4 Cloud Kit initializes that I'm stuggling to understand. I've spent most of the day finally getting a schema initialized on the server, and learnt a few things along the way.Firstly, even though I have a Default configuration in my managed object model, and it has been there from day one with the option "Used with CloudKit" checked for true, if I create an `NSPersistentStoreDescription` and set the configuration property to "Default", when I try to load the stores, it will fail, saying "Unable to find a configuration named 'Default' in the specified managed object model.". If I inpsect the debug description for my ManagedObjectModel instance, it does indeed not have any reference to the string "Default" in it (I'm not sure if debugDescription is actually printing out the configuration names however). Why does this fail? I can only get my store loaded and the schema initialized if I remove the code that sets the configuration name to "Default".The next thing that tripped me up was the NSPersistentCloudKitContainerOptions property on the store description. Considering that the only property on that class is now gone, so you no longer need to perform `options.shouldInitializeSchema = true`, I incorrectly assumed that I'd no longer need to even create and set a NSPersistentCloudKitContainerOptions instance on my store description, because all it really holds is the containerIdentifier. Why would I need to specify a container identifier if the system is going to fetch the first iCloud Container Identifier out of the entitlements file and associate it with the Default configuration which I'd (clearly incorrectly) assumed would be automatically associated with CloudKit and my "Default" entitlement container identifier.Below is the code I was using. It's mild playground refactor of my real code, but it's quite straightforward.// Instantiate the Managed Object Model let modelName = "CloudModel" let url = Bundle.main.url(forResource: modelName, withExtension: "momd") let mom: NSManagedObjectModel = NSManagedObjectModel(contentsOf: url!)! // Define the Cloud Store Description let storeURL = URL(fileURLWithPath: "Cloud.sqlite", isDirectory: false, relativeTo: NSPersistentContainer.defaultDirectoryURL()) let cloudStoreDescription = NSPersistentStoreDescription(url: storeURL) cloudStoreDescription.shouldAddStoreAsynchronously = true cloudStoreDescription.configuration = "Default" // this will cause loading to fail with an "Unable to find // a configuration named 'Default' in the specified managed object model." error // Add a container options instance to the description, because without it, loading will fail with // "Couldn't initialize CloudKit schema because no stores in the coordinator are configured to use CloudKit" var cloudKitOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "com.example.container.identifier") cloudStoreDescription.cloudKitContainerOptions = cloudKitOptions // Create the Container for the Cloud Store let container: NSPersistentCloudKitContainer = NSPersistentCloudKitContainer(name: modelName, managedObjectModel: mom) container.persistentStoreDescriptions = [cloudStoreDescription]
2
0
1.4k
Aug ’23
CoreData+CloudKit Model Migration Failing
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?
10
3
4.7k
Oct ’23
CoreData: warning: CoreData+CloudKit
I use NSPersistentCloudKitContainer. It seems that it the data synced in iCloud after a few seconds. However, I get the following warnings in the console. I do not understand what is it for. CoreData: warning: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(813): &lt;NSCloudKitMirroringDelegate: 0x280b051e0&gt;: Successfully set up CloudKit integration for store: &lt;NSSQLCore: 0x280024a00&gt; (URL: file:///private/var/mobile/Containers/Shared/AppGroup/89D9D17C-03DF-48E4-83C3-DB23A8FE0D6F/TestData.sqlite) CoreData: warning: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndScheduleImportIfNecessary:]_block_invoke(2033): &lt;NSCloudKitMirroringDelegate: 0x280b051e0&gt;: Scheduling automated import with activity: <CKSchedulerActivity: 0x281f51590; additionalXPCActivityCriteria={     Priority = Utility; }, containerID=&lt;CKContainerID: 0x283c612e0; containerIdentifier=iCloud.io.test.testData, containerEnvironment="Sandbox"&gt;, identifier=com.apple.coredata.cloudkit.activity.import, priority=2> Could you please explain what is this warning for and what should I do to fix it?
2
0
1.5k
Aug ’23
[NSPersistentCloudKitContainer] CloudKit integration forbids renaming 'OldEntityName' to 'NewEntityName'. Older devices can't process the new records. How to proceed?
I used a renaming identifier to rename an Entity Name, but it doesn't seem to work and it causes a crash at start during in-place migration. How to rename an Entity Name when using NSPersistentCloudKitContainer? I get this exception at start: CloudKit integration forbids renaming 'OldEntityName' to 'NewEntityName'. Older devices can't process the new records. Unresolved error Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." App is not in production, need a way to rename 'OldEntityName' to 'NewEntityName'. How to achieve this?
1
1
709
Sep ’23
Fix CloudKit container permissions
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
4
1
5.2k
Oct ’23
SwiftUI/CoreData: Simultaneous accesses to 0x7f92efc61cb8, but modification requires exclusive access
I'm working on an iOS app using SwiftUI and CoreData and am running into a problem that I cannot seem to figure out. To provide a little bit of information of what I am trying to do: I have two CoreData entities that have a One-To-Many relationship: Tarantula - A tarantula may molt many times (To Many) and when deleted, all of the molts shold also be removed (Cascade) Molt - A molt belongs to a single Tarantula (To One) and when deleted, should have the reference removed from the Tarantula (Nullify) I then have a view that lists all of the molts for a given Tarantula that allows adding and deleting molts. It looks like this: struct MoltListView: View { &#9;&#9;private static let DATE_FORMATTER: DateFormatter = { &#9;&#9;&#9;&#9;&#9;&#9;let d = DateFormatter() &#9;&#9;&#9;&#9;&#9;&#9;d.dateFormat = "MMM d, y" &#9;&#9;&#9;&#9;&#9;&#9;return d &#9;&#9;&#9;&#9;}() &#9;&#9; &#9;&#9;@Environment(\.managedObjectContext) private var viewContext &#9;&#9; &#9;&#9;@ObservedObject private var tarantula: Tarantula &#9;&#9;@FetchRequest private var molts: FetchedResults<Molt> &#9;&#9;@State private var userMessage: String = "" &#9;&#9;@State private var displayMessage: Bool = false &#9;&#9; &#9;&#9;init(tarantula: Tarantula) { &#9;&#9;&#9;&#9;self.tarantula = tarantula &#9;&#9;&#9;&#9;self._molts = FetchRequest(entity: Molt.entity(), &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; sortDescriptors: [NSSortDescriptor(keyPath: \Molt.date, ascending: false)], &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; predicate: NSPredicate(format: "tarantula = %@", tarantula)) &#9;&#9;} &#9;&#9; &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;List { &#9;&#9;&#9;&#9;&#9;&#9;Section(header: Text("Summary")) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text("\(molts.count) Molt\(molts.count == 1 ? "" : "s")") &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;Section(header: Text("Molts")) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;NavigationLink(destination: MoltView(tarantula: tarantula, molt: Molt.newModel())) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text("Add Molt").foregroundColor(.blue) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;ForEach(molts, id: \.self) { molt in &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;NavigationLink(destination: MoltView(tarantula: tarantula, molt: molt)) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;Text(MoltListView.DATE_FORMATTER.string(from: molt.modelDate)) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;.onDelete(perform: deleteItems) &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;}.alert(isPresented: $displayMessage) { &#9;&#9;&#9;&#9;&#9;&#9;Alert(title: Text("Save Failure"), message: Text(userMessage), dismissButton: .default(Text("Ok"))) &#9;&#9;&#9;&#9;} &#9;&#9;} &#9;&#9; &#9;&#9;private func deleteItems(offsets: IndexSet) { &#9;&#9;&#9;&#9;withAnimation { &#9;&#9;&#9;&#9;&#9;&#9;offsets.map { molts[$0] }.forEach(viewContext.delete) &#9;&#9;&#9;&#9;&#9;&#9;do { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;try viewContext.save() &#9;&#9;&#9;&#9;&#9;&#9;} catch { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;viewContext.rollback() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;userMessage = "\(error): \(error.localizedDescription)" &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;displayMessage.toggle() &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} &#9;&#9;} } The error I am experiencing comes from whenever I try to delete a molt from the list view. The app instantly crashes and the error is: Simultaneous accesses to 0x7f92efc61cb8, but modification requires exclusive access Find the complete error here: error - https://developer.apple.com/forums/content/attachment/6d74dcde-d82b-4024-ade0-5936d8926488 I have tried removing the animation block and have played around with removing different UI components/restructuring. The only way I have been able to prevent this error is to remove the delete rule on the Molt->Tarantula relationship from Nullify to No Action. However, this seems more like a hack to me instead of a fix. Was hoping for some help on this issue.
7
0
3.7k
Feb ’24
Core Data and Relationships
I've a large data feed to load in database. this data populate many entities that are related each others. I've follow this official tutorial - https://developer.apple.com/documentation/coredata/loading_and_displaying_a_large_data_feed to use nsbatchInsertRequest. But this tutorial has one big bug: populate data only in one entity. How many apps use a database with only one entity? therefore the problem that I have not only me, but several people, is time. With nsbatchinsertrequst I was able to insert more than 30000 records in just 5 seconds with a use of just 25MB of RAM. But without setting up relationships. if after the execution of the various insertrequests I set the relations, everything takes me about 50 seconds with an increase in memory to 60-70 MB. Is it possible that there is no way to quickly set up relationships? Not only that, this is a forum where Apple engineers, who therefore know the subject better, should give help. but who knows why, for such questions they disappear. Maybe it's my posts that are so boring that Apple ignores them? Or are they so difficult that even apple engineers can't solve them? Who knows if I'll ever find the answer! But is it possible that they don't have a solution? These Apple engineers if they had the same problem as me, how would they solve it? they simply say: "it can't be done! Arrange!"? anyway, I hope that some Apple engineer or someone experienced will be able to find the solution at least to this problem. Or it will be another zombie post in the billions of zombie posts of people like me who pay $ 100 but get no support. Thank you
2
1
1.5k
Aug ’23
Manually define a CKRecord ID for a given NSManagedObject instance
I have an app that is already running with CoreData, and I want to allow the users to upload their data to iCloud so, in the case they need to delete their apps or change devices, they don't lose it. Every time the app is opened, there is a synchronization that happens between CoreData and a JSON file fixture, in order to fill the app with its base values (creating NSManagedObject instances from the aforementioned fixture). Before the iCloud sync, the CoreData model had some constraints for different entities, to enforce uniqueness, but these had to be stripped since CloudKit doesn't support them. Most of these constraints were basically ids that came from the JSON and represent an item in our Firebase database. Given that, I want to make the underlying CKRecord.id the same as these ids, so I can avoid the situation where, if a person open the app in a second device, the fixture data is repeated, since the fixture runs before the sync with the iCloud happens. Is that possible? Any help would be appreciated.
6
0
1.4k
Mar ’24
NSPersistentCloudkitContainer Memory Leak -> Crash? (iOS 15 beta 4 & 5)
Background I have an established app in the App Store which has been using NSPersistentCloudkitContainer since iOS 13 without any issues. I've been running my app normally on an iOS device running the iOS 15 betas, mainly to see problems arise before my users see them. Ever since iOS 15 (beta 4) my app has failed to sync changes - no matter how small the change. An upload 'starts' but never completes. After a minute or so the app quits to the Home Screen and no useful information can be gleaned from crash reports. Until now I've had no idea what's going on. Possible Bug in the API? I've managed to replicate this behaviour on the simulator and on another device when building my app with Xcode 13 (beta 5) on iOS 15 (beta 5). It appears that NSPersistentCloudkitContainer has a memory leak and keeps ramping up the RAM consumption (and CPU at 100%) until the operating system kills the app. No code of mine is running. I'm not really an expert on these things and I tried to use Instruments to see if that would show me anything. It appears to be related to NSCloudkitMirroringDelegate getting 'stuck' somehow but I have no idea what to do with this information. My Core Data database is not tiny, but not massive by any means and NSPersistentCloudkitContainer has had no problems syncing to iCloud prior to iOS 15 (beta 4). If I restore my App Data (from an external backup file - 700MB with lots of many-many, many-one relationships, ckAssets, etc.) the data all gets added to Core Data without an issue at all. The console log (see below) then shows that a sync is created, scheduled & then started... but no data is uploaded. At this point the memory consumption starts and all I see is 'backgroundTask' warnings appear (only related to CloudKit) with no code of mine running. CoreData: CloudKit: CoreData+CloudKit: -[PFCloudKitExporter analyzeHistoryInStore:withManagedObjectContext:error:](501): <PFCloudKitExporter: 0x600000301450>: Exporting changes since (0): <NSPersistentHistoryToken - { "4B90A437-3D96-4AC9-A27A-E0F633CE5D9D" = 906; }> CoreData: CloudKit: CoreData+CloudKit: -[PFCloudKitExportContext processAnalyzedHistoryInStore:inManagedObjectContext:error:]_block_invoke_3(251): Finished processing analyzed history with 29501 metadata objects to create, 0 deleted rows without metadata. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _scheduleAutomatedExportWithLabel:activity:completionHandler:](2800): <NSCloudKitMirroringDelegate: 0x6000015515c0> - Beginning automated export - ExportActivity: <CKSchedulerActivity: 0x60000032c500; containerID=<CKContainerID: 0x600002ed3240; containerIdentifier=iCloud.com.nitramluap.Somnus, containerEnvironment="Sandbox">, identifier=com.apple.coredata.cloudkit.activity.export.4B90A437-3D96-4AC9-A27A-E0F633CE5D9D, priority=2, xpcActivityCriteriaOverrides={ Priority=Utility }> CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate executeMirroringRequest:error:](765): <NSCloudKitMirroringDelegate: 0x6000015515c0>: Asked to execute request: <NSCloudKitMirroringExportRequest: 0x600002ed2a30> CBE1852D-7793-46B6-8314-A681D2038B38 2021-08-13 08:41:01.518422+1000 Somnus[11058:671570] [BackgroundTask] Background Task 68 ("CoreData: CloudKit Export"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this. 2021-08-13 08:41:03.519455+1000 Somnus[11058:671570] [BackgroundTask] Background Task 154 ("CoreData: CloudKit Scheduling"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this. Just wondering if anyone else is having a similar issue? It never had a problem syncing an initial database restore prior to iOS 15 (beta 4) and the problems started right after installing iOS 15 (beta 4). I've submitted this to Apple Feedback and am awaiting a response (FB9412346). If this is unfixable I'm in real trouble (and my users are going to be livid). Thanks in advance!
22
0
10k
2w
[Core Data]: threw while encoding a value. with userInfo of (null)
I am getting the following error while saving data to CoreData. my model has the dictionary property. I created NSSecureCoding and NSSecureUnarchiveFromDataTransformer classes. please check if i can encode my model correctly. I couldn't understand what I am doing wrong ? The problem is not with Dictionary or Data properties. Why can't I save data to CoreData? I know little English. Thank you for your understanding. GitLab Project Link: It is a very simple one page project. I will be glad if you check it out. Core Data Test Project Console Output: 2021-08-21 23:58:18.490834+0300 CoreDataTest[35689:2901360] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x2827f0240> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x2827f0240> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Failed to save selected category: A Core Data error occurred. Core Data Entity: My Custom Model: Notice my model has a Dictionary. var sections: [QuestionSections.RawValue : String] I am trying to save dictionary in CoreData. I thought the problem was in the dictionary but the problem is not in the dictionary. class QuestionContainer: NSObject, Codable { var questionCategories: [Question] init(questionCategories: [Question]) { self.questionCategories = questionCategories } } public class Question: NSObject, Codable { var title: String var id: String var questions: [QuestionList] init(title: String, id: String, questions: [QuestionList]) { self.title = title self.id = id self.questions = questions } } public class QuestionList: NSObject, Codable { init(id: String, question: String, isQuestionImage: Bool, isSectionImage: Bool, imageURL: String, imageData: Data? = nil, sections: [QuestionSections.RawValue : String], selected: String, correct: String) { self.id = id self.question = question self.isQuestionImage = isQuestionImage self.isSectionImage = isSectionImage self.imageURL = imageURL self.imageData = imageData self.sections = sections self.selected = selected self.correct = correct } var id: String var question: String var isQuestionImage, isSectionImage: Bool var imageURL: String var imageData: Data? var sections: [QuestionSections.RawValue : String] var selected: String var correct: String } enum QuestionSections: String, Codable { case A = "A" case B = "B" case C = "C" case D = "D" } NSSecure Unarchive From Data Transformer: @objc(QuestionsValueTransformer) class QuestionsValueTransformer: NSSecureUnarchiveFromDataTransformer { static let name = NSValueTransformerName(rawValue: String(describing: QuestionsValueTransformer.self)) override static var allowedTopLevelClasses: [AnyClass] { return [QuestionsNSSecureCoding.self] } public static func register() { let transformer = QuestionsValueTransformer() ValueTransformer.setValueTransformer(transformer, forName: name) } } CoreData Save Function: func saveSelectedQuestion(questionTitle: String, id: String, questions: [QuestionList]) { let questionsCD = QuestionCD(context: persistentContainer.viewContext) questionsCD.title = questionTitle questionsCD.id = id questionsCD.questions = questions do { try persistentContainer.viewContext.save() } catch { print("Failed to save selected category: \(error.localizedDescription)") } }
1
0
1.9k
Jul ’23
How to deduplicate entities with relationships in NSPersistentCloudKitContainer?
In my app I have a defaultJournal: Journal, that automatically gets added on the user's device on launch. There should only be one "default" journal, and I know that deduplication as shown in the Apple Demo, is the correct approach to ensure this on multiple devices. Journal looks something like: class Journal: NSManagedObject { @NSManaged var isDefaultJournal: Bool @NSManaged var entries: Set<JournalEntry>? } Since Journal has a relationship to entries, how can I deduplicate it ensuring that I don't orphan or delete the entries? I am worried that the entries aren't guaranteed to be synced, when we discover a duplicate journal in processPersistentHistory. This would lead to either orphaned or deleted entries depending on the deletion rule. How can one handle deduplicating entities with relationships? For example here is my remove function:     func remove(duplicateDefaultCalendarNotes: [Journal], winner: Journal, on context: NSManagedObjectContext) {         duplicateDefaultCalendarNotes.forEach { journal in             defer { context.delete(journal) } // FIXME: What if all of the journal entries have not been synced yet from the cloud? // Should we fetch directly from CloudKit instead? (could still lead to orphaned/deleted journal that have not yet been uploaded)             guard let entries = journal.entries else { return }             entries.forEach {                 $0.journal = winner             }         }     } A missing tag on a post isn't that bad, but deleting a user's journal is unacceptable. What is the best strategy to handle this?
1
1
902
Sep ’23
CoreData: One or more models in this application are using transformable properties with transformer names that are either unset, or set to NSKeyedUnarchiveFromDataTransformerName.
My app is NOT using CoreData. But I'm seeing this fault error in Console.app from mac when I build my iOS app: CoreData: One or more models in this application are using transformable properties with transformer names that are either unset, or set to NSKeyedUnarchiveFromDataTransformerName. Please switch to using "NSSecureUnarchiveFromData" or a subclass of NSSecureUnarchiveFromDataTransformer instead. At some point, Core Data will default to using "NSSecureUnarchiveFromData" when nil is specified, and transformable properties containing classes that do not support NSSecureCoding will become unreadable. What could be the cause of it? What's the potential security issue it will cause to the app?
1
0
548
Sep ’23
SwiftUI Settings scene (Preferences): how call action when closed by user (click on red button or Cmd-W)
Hi, I thought this should be quite easy and maybe I only have tomatoes on my eyes, but I cannot find out how to call an action when the user clicks the red button or use CMD-W to close the Preferences window (= Settings Scene). I use Core Data. In the Preferences, many data structures, which define my system, are changed. I learned, that you shouldn't save too often to avoid performance problems, so now I want to save the Core Data context when the user closes the Preferences window. I tried .onDisappear, onChange of focus etc. but this didn't work. How can I define an action? Any hints are welcome :-)
2
0
1.1k
Apr ’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
How to put app-specific logic between migration steps?
There was a section in the talk about how we can break down migration into smaller changes, and that we have an opportunity to run app-specific code in between migration steps. However the talk didn't touch on how can can achieve this, besides a single sentence, which doesn't give enough detail at least for me to figure out how to do it. Intuitively, an event loop could be built that opens the persistent store with the lightweight migration options set and iteratively steps through each unprocessed model in a serial order, and Core Data will migrate the store. Given the automatic nature of the lightweight migrations, especially in the case where we're using NSPersistentCoordinator, doesn't the automatic system just zoom through all of the migrations from model A --> A' --> A'' -> B? How to we make it stop so we can execute our own app code? Thanks!
2
2
1k
Jan ’24
CoreData causing error running Mac App - Is there a way to reset app so it starts fresh?
Yesterday I had issues with my CoreData database for my Multiplatform app which resulted in changes to the schema. I reset the CloudKit version and, on the iOS simulator, had to delete my app and run the code again to get it to work. My issue is with the macOS target. I'm getting the same fatalError (Fatal error: Unresolved error Error Domain=NSCocoaErrorDomain Code=134140 "Persistent store migration failed, missing mapping model.") when running the macOS app but I can't figure out how to delete it so I can run it fresh like I did with the iOS version. I've found where the application is created (in the Debug directory ultimately within my app's Build directory) and removed them all but when run the newly created application has the same error. Should I move up the directory structure and remove the entire app directory within Xcode/DerivedData or is there another way? Wanted an answer before I do something I can't go back from :) Thanks, Kyra
2
1
1.8k
Nov ’23