Core Data

RSS for tag

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

Posts under Core Data tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SwiftUI NavigationLink freezing when tapped
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
12
2
6.0k
4d
"Failed to set up CloudKit integration" in TestFlight build
I'm building a macOS + iOS SwiftUI app using Xcode 14.1b3 on a Mac running macOS 13.b11. The app uses Core Data + CloudKit. With development builds, CloudKit integration works on the Mac app and the iOS app. Existing records are fetched from iCloud, and new records are uploaded to iCloud. Everybody's happy. With TestFlight builds, the iOS app has no problems. But CloudKit integration isn't working in the Mac app at all. No existing records are fetched, no new records are uploaded. In the Console, I see this message: error: CoreData+CloudKit: Failed to set up CloudKit integration for store: <NSSQLCore: 0x1324079e0> (URL: <local file url>) Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction.} I thought it might be that I was missing the com.apple.security.network.client entitlement, but adding that didn't help. Any suggestions what I might be missing? (It's my first sandboxed Mac app, so it might be really obvious to anyone but me.)
2
0
2.1k
Oct ’23
error: CoreData+CloudKit: Never successfully initialized and cannot execute request - incomprehensible archive
anyone getting the following error with CloudKit+CoreData on iOS16 RC? delete/resintall app, delete user CloudKit data and reset of environment don't fix. [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2044): <NSCloudKitMirroringDelegate: 0x2816f89a0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283abfa00> 41E6B8D6-08C7-4C73-A718-71291DFA67E4' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}
3
0
1.2k
5d
Not receiving Persistent Store Remote Change Notification.
Before the code... CloudKit, background mode (remote notifications) and push notifications are added to Capabilities. Background sync is working fine and view loads current store on manual fetch. Code that initialises the persistent container in app delegate... - (NSPersistentCloudKitContainer *)persistentContainer {     // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.     @synchronized (self) {         if (_persistentContainer == nil) {             _persistentContainer = [[NSPersistentCloudKitContainer alloc] initWithName:@"Expenses"];             [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {                 if (error != nil) {                     __block NSPersistentStoreDescription *sDescription = storeDescription;                     dispatch_async(dispatch_get_main_queue(), ^(){                         [sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"PersistentHistoryTracking"];                         [sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"NSPersistentStoreRemoteChangeNotificationOptionKey"];                     }); #ifdef DEBUG                     NSLog(@"Unresolved error %@, %@", error, error.userInfo); #endif                     abort();                 }                 else #ifdef DEBUG                     NSLog(@"Store successfully initialized"); #endif             }];         }     }     return _persistentContainer; } In Home view controller which is the initial view controller i am adding an observer for the remote notification...     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadViewONCKChangeNotification) name:NSPersistentStoreRemoteChangeNotification object:[appDelegate.persistentContainer persistentStoreCoordinator]]; I am not receiving any store change notifications. Have added breakpoints to see if selector is fired. no go. CloudKit Console also doesn't show any pushes for the concerned time period.
4
0
1.2k
Jan ’24
Swift Concurrency, Core Data, "partially thread-safe" types & Sendable conformance
Hi, Xcode warns me that NSPersistentContainer, NSManagedObjectContext, NSPersistentHistoryTransaction and NSPersistentHistoryToken are non-Sendable types and therefore cannot cross actor boundaries. These warnings occur even when I use @preconcurrency import CoreData (only works with Xcode 14.0 Beta, in Xcode 13.4.1, it says '@preconcurrency' attribute on module 'CoreData' is unused) I understand that types in Core Data have yet to be marked as Sendable when it makes sense. Although NSPersistentHistoryTransaction, and NSPersistentHistoryToken are reference types, they should qualify to be marked as Sendable in the future since these are immutable types, am I right? NSPersistentContainer provides variables and methods like viewContext and newBackgroundContext(). It would make sense that this type is thread-safe. However, I'm not sure about it, especially regarding its loadPersistentStores(completionHandler:) method. Is NSPersistentContainer (and its subclass NSPersistentCloudKitContainer) thread-safe and should it be marked as Sendable in the future? The case of and NSManagedObjectContext confuses me the most. Indeed, it has both thread-safe methods like perform(_:) and thread-unsafe methods like save(). Still, it should be possible to cross actor boundaries. Would such a "partially thread-safe" type quality to be marked as Sendable? If not, how can it cross actor boundaries? The reason I'm asking these questions is that I have a CoreDataStack type. It has mutable variables, such as var lastHistoryToken: NSPersistentHistoryToken?, needs to perform work without blocking the main thread, such as writing the token to a file, has async methods, uses notification observers, and needs to be marked as Sendable to be used by other controllers running on different actors. Since this type is related to back-end work, I made it an Actor. This type exposes the persistent container, and a method to create new background threads. However, I need to explicitly annotate all methods using await context.perform { ... } as nonisolated in this actor. Not doing so causes a data race to be detected at runtime. Is this a bug, and is making a Core Data stack an Actor the proper way to do it or is there a better solution? Any help would be greatly appreciated. Thanks. Xcode Configuration Xcode 13.4.1, Xcode 14.0 beta 5 The Xcode project is configured with Other Swift Flags set to -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks.
4
2
2.6k
Oct ’23
NSCocoaErrorDomain code = 134093 , only in iOS16
i have received a lot of crash log only in iOS16 the crash occured when i called : [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:resultHandler] here is the crash log Exception Type: NSInternalInconsistencyException ExtraInfo: Code Type: arm64 OS Version: iPhone OS 16.0 (20A5328h) Hardware Model: iPhone14,3 Launch Time: 2022-07-30 18:43:25 Date/Time: 2022-07-30 18:49:17 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:Unhandled error (NSCocoaErrorDomain, 134093) occurred during faulting and was thrown: Error Domain=NSCocoaErrorDomain Code=134093 "(null)" Last Exception Backtrace: 0 CoreFoundation 0x00000001cf985dc4 0x1cf97c000 + 40388 1 libobjc.A.dylib 0x00000001c8ddfa68 0x1c8dc8000 + 96872 2 CoreData 0x00000001d56d2358 0x1d56cc000 + 25432 3 CoreData 0x00000001d56fa19c 0x1d56cc000 + 188828 4 CoreData 0x00000001d5755be4 0x1d56cc000 + 564196 5 CoreData 0x00000001d57b0508 0x1d56cc000 + 935176 6 PhotoLibraryServices 0x00000001df1783e0 0x1df0ed000 + 570336 7 Photos 0x00000001df8aa88c 0x1df85d000 + 317580 8 PhotoLibraryServices 0x00000001df291de0 0x1df0ed000 + 1723872 9 CoreData 0x00000001d574e518 0x1d56cc000 + 533784 10 libdispatch.dylib 0x00000001d51fc0fc 0x1d51f8000 + 16636 11 libdispatch.dylib 0x00000001d520b634 0x1d51f8000 + 79412 12 CoreData 0x00000001d574e0a0 0x1d56cc000 + 532640 13 PhotoLibraryServices 0x00000001df291d94 0x1df0ed000 + 1723796 14 PhotoLibraryServices 0x00000001df291434 0x1df0ed000 + 1721396 15 Photos 0x00000001df8a8380 0x1df85d000 + 308096 16 Photos 0x00000001df89d050 0x1df85d000 + 262224 17 Photos 0x00000001df87f62c 0x1df85d000 + 140844 18 Photos 0x00000001df87ee94 0x1df85d000 + 138900 19 Photos 0x00000001df87e594 0x1df85d000 + 136596 20 Photos 0x00000001df86b5c8 0x1df85d000 + 58824 21 Photos 0x00000001df86d938 0x1df85d000 + 67896 22 Photos 0x00000001dfa37a64 0x1df85d000 + 1944164 23 Photos 0x00000001dfa37d18 0x1df85d000 + 1944856 24 youavideo -[YouaImageManager requestImageDataForAsset:options:resultHandler:] (in youavideo) (YouaImageManager.m:0) 27 25 youavideo -[YouaAlbumTransDataController requstTransImageHandler:] (in youavideo) (YouaAlbumTransDataController.m:0) 27 26 youavideo -[YouaAlbumTransDataController requstTransWithHandler:] (in youavideo) (YouaAlbumTransDataController.m:77) 11 27 youavideo -[YouaUploadTransDataOperation startTrans] (in youavideo) (YouaUploadTransDataOperation.m:102) 19 28 Foundation 0x00000001c9e78038 0x1c9e3c000 + 245816 29 Foundation 0x00000001c9e7d704 0x1c9e3c000 + 268036 30 libdispatch.dylib 0x00000001d51fa5d4 0x1d51f8000 + 9684 31 libdispatch.dylib 0x00000001d51fc0fc 0x1d51f8000 + 16636 32 libdispatch.dylib 0x00000001d51ff58c 0x1d51f8000 + 30092 33 libdispatch.dylib 0x00000001d51febf4 0x1d51f8000 + 27636 34 libdispatch.dylib 0x00000001d520db2c 0x1d51f8000 + 88876 35 libdispatch.dylib 0x00000001d520e338 0x1d51f8000 + 90936 36 libsystem_pthread.dylib 0x00000002544b9dbc 0x2544b9000 + 3516 37 libsystem_pthread.dylib 0x00000002544b9b98 0x2544b9000 + 2968 i can't find the error code 134093 definition i don't know what's going wrong in iOS16 Would anyone have a hint of why this could happen and how to resolve it? thanks very much
7
5
2.8k
Jun ’24
CoreData CloudKit sync resulting in main thread initialisation issue
I'm using Xcode 14 beta 4, on macOS Monterey 12.5, developing a Mac app that's using CoreData CloudKit sync — with my context being configured with two configurations (one for a local cache and one data synced via CloudKit). An issue recently appeared where the app crashes soon after start-up with this message: [threadmgrsupport] _TSGetMainThread_block_invoke:Main thread potentially initialized incorrectly, cf <rdar://problem/67741850> And this stack trace: Thread 1 Queue : com.apple.main-thread (serial) #0 0x000000018b86b5e8 in ___NSAssertMainEventQueueIsCurrentEventQueue_block_invoke () #1 0x0000000105b563a8 in _dispatch_client_callout () #2 0x0000000105b58300 in _dispatch_once_callout () #3 0x000000018b86a2dc in _DPSNextEvent () #4 0x000000018b868e14 in -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] () #5 0x000000018b85afe0 in -[NSApplication run] () #6 0x000000018b82c6fc in NSApplicationMain () #7 0x00000001ae281e98 in specialized runApp(_:) () #8 0x00000001aee10588 in runApp<τ_0_0>(_:) () #9 0x00000001ae88626c in static App.main() () Things work again, if I disable the CloudKit sync by not setting cloudKitContainerOptions on my "Cloud" configuration. Similarly, it works on first install, but reappears on subsequent runs. The code is in a package that's shared with an iOS version of the app, which has no such issues. I also tried going back to previous commits that worked before, and it works again until at some point it stops working again for the same commits. So it doesn't seem to be caused directly by my code, but rather by something that the CloudKit sync is doing. Any help would be much appreciated.
3
2
2.0k
Oct ’23
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.7k
Nov ’23
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
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
1w
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
1k
Apr ’24
CloudKit: how to handle CKError partialFailure when using NSPersistentCloudKitContainer?
I'm using NSPersistentCloudKitContainer with Core Data and I receive errors because my iCloud space is full. The errors printed are the following: <CKError 0x280df8e40: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = 61846C533467A5DF; uuid = 6A144513-033F-42C2-9E27-693548EF2150; Retry after 342.0 seconds>. I want to inform the user about this issue, but I can't find a way to access the details of the error. I'm listening to NSPersistentCloudKitContainer.eventChangedNotification, I receive a error of type .partialFailure. But when I want to access the underlying errors, the partialErrorsByItemID property on the error is nil. How can I access this Quota Exceeded error? import Foundation import CloudKit import Combine import CoreData class SyncMonitor { fileprivate var subscriptions = Set<AnyCancellable>() init() { NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification) .sink { notification in if let cloudEvent = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event { guard let ckerror = cloudEvent.error as? CKError else { return } print("Error: \(ckerror.localizedDescription)") if ckerror.code == .partialFailure { guard let errors = ckerror.partialErrorsByItemID else { return } for (_, error) in errors { if let currentError = error as? CKError { print(currentError.localizedDescription) } } } } } // end of sink .store(in: &subscriptions) } }
1
1
1.1k
Jul ’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
526
Sep ’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
860
Sep ’23
[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.8k
Jul ’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.3k
Mar ’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.4k
Aug ’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.6k
Feb ’24