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

217 Posts
Sort by:
Post not yet marked as solved
2 Replies
1.6k Views
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
Posted
by
Post marked as solved
3 Replies
1.9k Views
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.
Posted
by
Post not yet marked as solved
5 Replies
2.6k Views
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
Posted
by
Post not yet marked as solved
1 Replies
2.4k Views
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.
Posted
by
Post marked as solved
4 Replies
1.1k Views
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.
Posted
by
Post not yet marked as solved
1 Replies
641 Views
I have the below fetch request which I want to be able to dynamically change the setup of. The request is setup initially as         sectionIdentifier: \.level,         sortDescriptors: [NSSortDescriptor(keyPath: \Card.level, ascending: true),                           NSSortDescriptor(keyPath: \Card.setID, ascending: true),                           NSSortDescriptor(keyPath: \Card.cardID, ascending: true),                           NSSortDescriptor(keyPath: \Card.name, ascending: true)],         animation: .default)     private var cards: SectionedFetchResults<Int16, Card> I've got the predicate change working fine, but get errors with the sort descriptors and the section identifier On setting the sort descriptors I get the error Cannot convert value of type 'NSSortDescriptor' to expected element type 'Array<SortDescriptor>.ArrayLiteralElement' (aka 'SortDescriptor') And setting the section identifier I get Cannot assign value of type 'SectionedFetchResults<String, Card>.Type' to type 'KeyPath<Card, Int16>' The code I have is below.                 if groupBy == 2 {                     cards.nsPredicate = nil                     let sortSetID = NSSortDescriptor(keyPath: \Card.setID, ascending: true)                     let sortName = NSSortDescriptor(keyPath: \Card.name, ascending: true)                     cards.sortDescriptors = [sortSetID, sortName] // This errors                     cards.sectionIdentifier = SectionedFetchResults<String, Card> // This errors                 }
Posted
by
Post marked as solved
2 Replies
1.8k Views
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.)
Posted
by
Post not yet marked as solved
5 Replies
5.0k Views
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.
Posted
by
ngb
Post marked as solved
1 Replies
910 Views
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!
Posted
by
Post not yet marked as solved
3 Replies
1.3k Views
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.
Posted
by
Post not yet marked as solved
1 Replies
965 Views
I'm working on a Core Data / CloudKit public Database. Apple recommends not to delete the object but to set a variable e.g. isTrashed to true. After that a predicate should be set for the FetchRequest so that this object is no longer displayed. So in my view I set this variable to true when an object is deleted and this is also set correctly. Here is the query directly from the dashboard: Unfortunately the predicate doesn't work as it should and the object is still displayed. Can anyone tell me what I am doing wrong? Fetch Request static var productsByName: NSFetchRequest<Product> { /// create Request let request: NSFetchRequest<Product> = Product.fetchRequest() /// sortDescriptor request.predicate = NSPredicate(format: "isTrashed = false") // <-- predicate for isTrashed request.sortDescriptors = [NSSortDescriptor(keyPath: \Product.name, ascending: true)] return request } ContentView.swift struct ContentView: View { @SectionedFetchRequest(fetchRequest: ContentView.productsByName, sectionIdentifier: \Product.manufacturer?.name) var products: SectionedFetchResults<String?, Product> var body: some View { NavigationStack { List { ForEach(products) { section in Section(header: Text(section.id ?? "unassigned")) { ForEach(section) { product in NavigationLink(destination: productDetailView(product: product)){ Text(product.name ?? "na") } } .onDelete { rows in for row in rows { let product = section[row] if storageProvider.persistentContainer.canDeleteRecord(forManagedObjectWith: product.objectID) { storageProvider.deleteProduct(product) } else { product.isTrashed = true // <-- here the value for isTrashed is set do { try storageProvider.persistentContainer.viewContext.save() } catch { storageProvider.persistentContainer.viewContext.rollback() print("Failed to save context: \(error)") } } } } } } } } } } info 1 additional info: I added this code to the detailView of the products to check if the value is set correct: Text("is trashed: \(product.isTrashed ? "true" : "false")") ... and yes it is: info 2 I also tried these for the query: request.predicate = NSPredicate(format: "isTrashed = 0") request.predicate = NSPredicate(format: "isTrashed = FALSE") request.predicate = NSPredicate(format: "isTrashed = NO") request.predicate = NSPredicate(format: "isTrashed = 0") request.predicate = NSPredicate(format: "isTrashed == FALSE") request.predicate = NSPredicate(format: "isTrashed == NO") request.predicate = NSPredicate(format: "%K = %@", argumentArray: [#keyPath(Product.isTrashed), false]) request.predicate = NSPredicate(format: "%K == %@", argumentArray: [#keyPath(Product.isTrashed), false]) So I don't think the query itself is the problem :/ info 3 but for example this predicate directly on the view is working: .onReceive(productName.$debounced) { query in /// don't filter when searchbar is empty guard !query.isEmpty else { products.nsPredicate = nil return } /// set filter when someone searches products.nsPredicate = NSPredicate(format: "%K CONTAINS[cd] %@", argumentArray: [#keyPath(Product.name), query]) } That's why I don't understand why the predicate on the FetchRequest isn't working. Does anyone have an idea?
Posted
by
Post not yet marked as solved
1 Replies
519 Views
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!
Posted
by
Post not yet marked as solved
1 Replies
1.2k Views
I'm experiencing a weird issue on iOS16. There is no code change, it works fine on lower OS versions. The stack traces are: The first case: Crashed: com.apple.main-thread EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000e5bde410 0 libobjc.A.dylib objc_release_x21 + 16 1 CoreData -[_PFManagedObjectReferenceQueue _processReferenceQueue:] + 1020 2 CoreData -[NSManagedObjectContext _processRecentChanges:] + 112 3 CoreData _performRunLoopAction + 412 4 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 36 5 CoreFoundation __CFRunLoopDoObservers + 532 6 CoreFoundation __CFRunLoopRun + 1048 7 CoreFoundation CFRunLoopRunSpecific + 612 8 GraphicsServices GSEventRunModal + 164 9 UIKitCore -[UIApplication _run] + 888 10 UIKitCore UIApplicationMain + 340 The second case, I believe this stack trace has the same root cause as the previous one (same trend, same UI page, only happens on iOS 16). Crashed: com.apple.main-thread EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0033003200390070 0 libobjc.A.dylib objc_msgSend + 32 1 CoreFoundation -[__NSArrayM dealloc] + 188 2 MyApplication MyClass.m - Line 361 -[MyClass loadMessages:] + 361 3 MyApplication MyClass.m - Line 125 __74-[MyClass requestRecentMessagesAndDiscardExistingMessagesCompletion:]_block_invoke + 125 4 libdispatch.dylib _dispatch_call_block_and_release + 32 5 libdispatch.dylib _dispatch_client_callout + 20 6 libdispatch.dylib _dispatch_main_queue_drain + 928 7 libdispatch.dylib _dispatch_main_queue_callback_4CF + 44 8 CoreFoundation __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 9 CoreFoundation __CFRunLoopRun + 2036 10 CoreFoundation CFRunLoopRunSpecific + 612 11 GraphicsServices GSEventRunModal + 164 12 UIKitCore -[UIApplication _run] + 888 13 UIKitCore UIApplicationMain + 340 MyClass.m is an Objective-C class, it has a property: @property (nonatomic, strong) NSArray&lt;Message *&gt; *messages; // Message is NSManagedObject In the second stacktrace, frame -[OurClass loadMessages:] + 361, the messages array is deallocated: self.messages = [[NSArray alloc] init...]; So my guess is, somehow the messages are over-released. If the messages are released in MyClass before, then the crash happens as the first stack trace, otherwise, it happens as the second stack trace. I've turned on -com.apple.CoreData.ConcurrencyDebug 1 to try to find out the concurrency issues and fixed them, but no luck. Any help would be much appreciated. Thanks in advance!
Posted
by
Post not yet marked as solved
5 Replies
715 Views
I'm trying to follow the steps here https://developer.apple.com/documentation/coredata/setting_up_a_core_data_stack?language=objc for setting up core data using objective c, using the boilerplate given by xcode when opting into core data, but it appears to only show swift. The main view controller I have is of class TodoListTableViewController, which is storyboard-generated, which is embedded in a navigation controller like so: entrypoint-&gt;navigation controller-&gt;TodoListTableViewController I tried defining my AppDelegate::applicationDidFinishLaunchingWithOptions like so: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (self.persistentContainer == nil) { [NSException raise:@"did not initialize persistent container in app delegate" format:@"no init"]; } UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; TodoListTableViewController *todoListVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"TodoListTableViewController"]; todoListVC.persistentContainer = self.persistentContainer; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:todoListVC]; self.window.rootViewController = navController; return YES; } and using the boilerplate in AppDelegate @synthesize persistentContainer = _persistentContainer; - (NSPersistentContainer *)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 = [[NSPersistentContainer alloc] initWithName:@"ToDoList"]; [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) { if (error != nil) { // Replace this implementation with code to handle the error appropriately. // abort() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ NSLog(@"Unresolved error %@, %@", error, error.userInfo); abort(); } }]; } } return _persistentContainer; } #pragma mark - Core Data Saving support - (void)saveContext { NSManagedObjectContext *context = self.persistentContainer.viewContext; NSError *error = nil; if ([context hasChanges] &amp;&amp; ![context save:&amp;error]) { // Replace this implementation with code to handle the error appropriately. // abort() 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. NSLog(@"Unresolved error %@, %@", error, error.userInfo); abort(); } } but I'm getting a missing container exception since I added a check for the existence of persistentContainer in TodoListTableViewController like so: - (void)viewDidLoad { [super viewDidLoad]; if (self.persistentContainer == nil) { [NSException raise:@"missing container" format:@"missing container"]; } } thank you.
Posted
by
Post marked as solved
3 Replies
1.1k Views
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?
Posted
by
Post not yet marked as solved
2 Replies
1.5k Views
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
Posted
by
Post not yet marked as solved
3 Replies
845 Views
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?
Posted
by
Post not yet marked as solved
0 Replies
455 Views
We have a core data entity with an attribute "description" with very very large string stored. When we try to filter the entities with a predicate format such as "description contains ***" then it takes around 20 seconds time when the number of rows are above 10000. To improve the speed we tried adding index to description, but it took actually more time than querying without index. Not sure it is because of "contains" predicate. We also have a requirement of fetching all the matching rows immediately. So we cannot use fetchLimit. Is there any alternative to fetchrequest predicate? Is there any better ways to make the fetchrequest faster? Please suggest Thanks Vinoth
Posted
by
Post not yet marked as solved
0 Replies
424 Views
I recently started to learn CoreData with CloudKit in SwiftUI. It seems to be still quite a young solution (I know CoreData itself has been around for over a decade), so apart from some limited resources within the official documentation and archive, I get most information from the web. One thing that I had trouble with was storing in CoreData moderately complex data received in JSON format. Although I read that CoreData itself is not a relational database, it does look much alike to me, so my first choice would be to use relationships, but I saw people store arrays of data using attributes instead, e.g., in this StackOverflow thread. In my case, it would be an array of custom datatype objects, and while some resources on the web were helpful to get me quite far (e.g. this), I couldn't pull it off in the end. My question after this long background story is — in what situations would I choose attributes for storing collections of data instead of relationships? As an example, I currently have an entity Food in a to-many relationship with an entity Portion (a cup of rice, 8 oz of rice, etc.)
Posted
by
Post not yet marked as solved
2 Replies
357 Views
I am experiencing a very weird issue with Core Data. I created a simple POC application to check this better. I am using a simple FetchedResultsController as Data Source for the View Controller to show the Data. I am using a background thread (performBackgroundTask) to add an entity, when a user inputs it. Also am using automaticallyMergesChangesFromParent (or transaction history) to merge the data added from the background context to the viewContext - the wrong behaviour will be the same for any of the two options used. The application runs fine, whenever I add an entity, I see in the SQL log a notification, and the query which is triggered automatically for the FetchedResultsController, and UI is updated with the new record. Now if I crash the application exactly while a record is being added to the database - it is hard to pinpoint the moment exactly - after this point on, I restart the application, and whenever I add one more entity, the application also works fine except that the fetch query executed by the FetchedResultsController is repeated several times (had use case where I had it repeat for several seconds). I get no errors from the PersistentController, or anything that the SQL Database is corrupted; data base browsers also do not show anything suspicious, except the gap in the record primary key (index) of the missing record which was attempted to be added when the crash occurred - which is missing in the number continuity. If I reinstall the application / delete the SQL store the app works fine. I also created a git repo for this POC - ready to download and try out: https://github.com/warlockba/CoreDataPOC.git Is there some way in Core Data to execute some kind of "repair" or "integrity check"? Because I have no further idea how to fix / recognise / detect the issue - since nothing is throwing any errors, except this huge amount of fetches, after the issue happens. Thanks, Andrei
Posted
by