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

Core Data foreign key/relationship between two tables
hi, this is a very simple concept that I can't seem to solve using relationships with core data between two tables. for instance, I have a client table with a name field that I want to link to a client details table with a clientName field and when I update/edit the client name, this still stays links to the client details record. make sense? I tried relationships but it does not link up when I edit the client name. I feel like I'm missing something very obvious here and have tried multiple scenarios but I'm not finding a solution nor am I finding any documentation on how this should work. any help/ideas is appreciated. Thank you, Pete
0
0
413
Aug ’23
Can I access CloudKit's metadata fields with NSPersistentCloudKitContainer?
I've got a simple Core Data Entity that is synchronized with CloudKit via NSPersistentCloudKitContainer. I can read my local fields, but how can I read fields like "Created" & "Modified" from CloudKit? Do I have to add them to my Core Data model and populate them myself? P.S. In his fantastic WWDC talk "Using Core Data with CloudKit", at around 21:40, Nick Gillet talks about how Core Data entities in the CloudKit store are prefixed with "CD_" to separate the things that it manages from the ones CloudKit implements. Then he says: "You wouldn't believe how many people add modify date to their CKRecord". Like it's something redundant.
0
0
420
Aug ’23
cannot push coredata records to cloudkit
coredata pushed schema to cloudkit only for those entities for which I created records. But the record data did not get pushed. I set recordName as Queryable and modifiedTimestamp as both Queryable and sortable. Query does not show the records. I look at Xcode console gives this output for one of the entities that got pushed to cloudkit : CoreData: debug: CoreData+CloudKit: -[PFCloudKitSerializer newCKRecordsFromObject:fullyMaterializeRecords:includeRelationships:error:](575): Serializer has finished creating record: <CKRecord: 0x13f40f920; recordType=CD_Contact, recordID=26809600-B329-4C17-B3E1-6EA5FC177F7C:(com.apple.coredata.cloudkit.zone:__defaultOwner__), values={ "CD_contact" = "26809600-B329-4C17-B3E1-6EA5FC177F7C"; "CD_contactEmail_ckAsset", "CD_contact", "CD_contactEmail", "<CKRecord: 0x13f40f920; recordType=CD_Contact, recordID=26809600-B329-4C17-B3E1-6EA5FC177F7C:(com.apple.coredata.cloudkit.zone:__defaultOwner__), recordChangeTag=5, values={\n \"CD_email\" = Email;\n \"CD_entityName\" = Contact;\n \"CD_firstName\" = V;\n \"CD_imageName\" = \"{ length=20834, sha256=d582bd2ccc7d93138b3a5ad4799443152860268e34f48ace54a0708f3e2f3aba }\";\n \"CD_lastName\" = R;\n \"CD_phone\" = 2;\n \"CD_screenName\" = Vr;\n \"CD_userRating\" = \"*****\";\n \"CD_userType\" = Household;\n}>", Also schema for some other entities that do not have any core data records did not get pushed to CloudKit. I thought the entire coredata schema should get pushed along with the records. Looks like it is pushing those entities that have some records but without pushing data. I reset the cloudkit environment and tried again, but issue is not resolved. Also the AppDelegate never gets called. I thought the line below should have called AppDelegate @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate: AppDelegate Cross referenced persistenceController in AppDelegate. That did not help either Code listed below. Please let me know how to fix the above two issues? main struct GreenApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate: AppDelegate static var fcmToken: String? let gcmMessageIDKey = "gcm.Message_ID" let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } } struct PersistenceController { static let shared = PersistenceController() static var preview: PersistenceController = { let result = PersistenceController(inMemory: true) let viewContext = result.container.viewContext // for _ in 0..<10 { // let newItem = Item(context: viewContext) // newItem.timestamp = Date() // } do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } return result }() let container: NSPersistentCloudKitContainer init(inMemory: Bool = false) { container = NSPersistentCloudKitContainer(name: "Green") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy // external changes trumping in-memory changes. } } Appdelegate code: class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, ObservableObject { static var fcmToken: String? let gcmMessageIDKey = "gcm.Message_ID" let persistenceController = PersistenceController.shared func applicationDidFinishLaunching(_ application: UIApplication) { do { // Use the container to initialize the development schema. try persistenceController.container.initializeCloudKitSchema(options: []) } catch { // Handle any errors. fatalError("###\(#function): failed to load persistent stores: \(error)") } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types:[.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } DispatchQueue.main.async { application.registerForRemoteNotifications() } } }
2
0
695
Aug ’23
Save object to shared database
Maybe I'm going about this completely the wrong way but I've got two stores loaded in my app: private and shared. I've got zone-wide sharing enabled and I can update records that exist in the shared database (on the participant device), and see updates sync when changed by the owner. However, is it possible to save a new object specifically to the shared database as the participant? If I create a new object in my managed object context it saves it to the private database. Can provide code if needed but it's more conceptual at this stage.
1
0
695
Aug ’23
Has anyone successfully used NSStagedMigrationManager?
I've been trying to build an example of NSStagedMigrationManager from some Core Data migration tests to replace a custom migration manager solution I'd constructed, without much success. The Core Data model has seven model versions. Most support lightweight migration, but two of the migrations in the middle of the sequence used NSMappingModel. In the first beta, just attempting to construct an NSStagedMigrationManager from the series of stages failed with an unrecognized selector. That no longer happens in b4, but I now get an error that "Duplicate version checksums across stages detected." If I restrict myself to just the first three versions of the model (that only require lightweight migration), I can build the migration manager. But if I attempt to use it to migrate a persistent store, it fails somewhere in NSPersistentStoreCoordinator with a nilError. The documentation is almost nonexistent for this process, and the WWDC session that introduced it isn't much more than a breezy overview. So maybe I'm holding it wrong? (And, yes: FB12339663)
5
0
1.1k
Feb ’24
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.3k
Oct ’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
1.1k
Feb ’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
743
Sep ’23
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
2k
May ’24
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
633
May ’24
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
968
Oct ’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.9k
3w
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.3k
Sep ’23
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
616
Oct ’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.
4
1
1.5k
May ’24
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
1k
Nov ’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
6.4k
3w