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

360 Posts
Sort by:
Post not yet marked as solved
2 Replies
2.9k Views
Hi all,I am making an app which is fetching all contacts phone numbers.From all contacts I am making a competition that people can make with their phone contacts.Can someone advice how to fetch all phone numbers using CNContactStore?Thanks,Boban
Posted
by
Post not yet marked as solved
5 Replies
1.5k Views
Hi Guys,I am testing a document-based CoreData database with iCloud-UIManagedDocument (using Swift 2) but the document it creates is initially a directory with the database files in it. But i’am looking for the single-file type. Does anyone know how to change the internal filewrapper to build a single-file document? One of the problems is that CoreData adds some extra SHM and WAL files from time to time and the second problem is that database files are not just flatfile types.Hope someone can help me out
Posted
by
Post not yet marked as solved
3 Replies
1.3k Views
I finally got around to trying out the new query generations in iOS 10 but when I turned it on, I started getting exceptions when calling mergeChanges(fromContextDidSave:). My app supports iOS 9 as well so I can't use NSPersistentContainer quit yet. Here's where I am setting up the Core Data stack: (also at https://gist.github.com/davbeck/85adfe8ab723562abf7c998e53f8e9f5) / static func defaultStoreURL() -> URL? { do { guard var url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else { return nil } url.appendPathComponent("EngagementData") try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) url.appendPathComponent("Data.sqlite3") return url } catch { return nil } } public let storeURL: URL? public let managedObjectModel: NSManagedObjectModel = { let momURL = Bundle(for: APIClient.self).url(forResource: "Realm", withExtension: "momd")! return NSManagedObjectModel(contentsOf: momURL)! }() fileprivate(set) open lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let options = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true, ] if let storeURL = self.storeURL { do { self.logger.info("storeURL: \(self.storeURL)") try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.storeURL, options: options) return persistentStoreCoordinator } catch let error { self.logger.error("Could not create NSPersistentStoreCoordinator", error: error) } } / try! persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) return persistentStoreCoordinator }() fileprivate(set) public lazy var backgroundContext: NSManagedObjectContext = { let context = ManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) context.persistentStoreCoordinator = self.persistentStoreCoordinator context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy context.dispatchGroup = self.dispatchGroup context.shouldDeleteInaccessibleFaults = true if #available(iOS 10, *) { do { try context.setQueryGenerationFrom(.current) } catch { self.logger.error("could not activate query generation", error: error) } } return context }() public func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) { self.backgroundContext.perform { block(self.backgroundContext) } } fileprivate(set) public lazy var viewContext: NSManagedObjectContext = { let context = ManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = self.persistentStoreCoordinator context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy context.dispatchGroup = self.dispatchGroup context.shouldDeleteInaccessibleFaults = true if #available(iOS 10, *) { do { try context.setQueryGenerationFrom(.current) } catch { self.logger.error("could not activate query generation", error: error) } } return context }() / func viewContextDidSave(_ notification: Notification) { self.logger.debug("viewContextDidSave: \(notification.userInfo)") self.backgroundContext.perform { self.backgroundContext.mergeChanges(fromContextDidSave: notification) } } func backgroundContextDidSave(_ notification: Notification) { self.logger.debug("backgroundContextDidSave: \(notification.userInfo)") self.viewContext.perform { self.viewContext.mergeChanges(fromContextDidSave: notification) } }Inside of backgroundContextDidSave, self.viewContext.mergeChanges(fromContextDidSave: notification) causes an EXC_BAD_INSTRUCTION and prints out "More code needs to be written". Am I missing something? What other code needs to be written?!?!
Posted
by
Post not yet marked as solved
0 Replies
1.1k Views
In my latest app update I have a few users complaining about crashes and I managed to get my hands on a crash report. Here's the crash reason from the symbolicated crash log. Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d Triggered by Thread: 0This happens when I call `[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:]`Here's the complete stacktrace: Thread 0 name: Dispatch queue: SQLQueue 0x12fecca10 for .database.db.migrationdestination_41b5a6b5c6e848c462a8480cd24caef3 Thread 0 Crashed: 0 libsystem_kernel.dylib 0x0000000180640164 __fcntl + 8 1 libsystem_kernel.dylib 0x0000000180625660 fcntl + 84 2 libsqlite3.dylib 0x0000000181ba3f90 0x181b3d000 + 421776 3 libsqlite3.dylib 0x0000000181bb9e50 0x181b3d000 + 511568 4 libsqlite3.dylib 0x0000000181bcdf34 0x181b3d000 + 593716 5 libsqlite3.dylib 0x0000000181bcdd98 sqlite3_wal_checkpoint_v2 + 492 6 libsqlite3.dylib 0x0000000181ba41b0 0x181b3d000 + 422320 7 libsqlite3.dylib 0x0000000181b7b288 sqlite3_step + 976 8 CoreData 0x000000018391b194 _execute + 164 9 CoreData 0x000000018394ffd8 -[NSSQLiteConnection commitTransaction] + 312 10 CoreData 0x0000000183a6ced8 __43-[_NSSQLiteStoreMigrator performMigration:]_block_invoke + 2784 11 CoreData 0x0000000183a36cbc __37-[NSSQLiteConnection performAndWait:]_block_invoke + 40 12 libdispatch.dylib 0x00000001804fe9a0 _dispatch_client_callout + 16 13 libdispatch.dylib 0x000000018050bee0 _dispatch_barrier_sync_f_invoke + 84 14 CoreData 0x0000000183a36c08 -[NSSQLiteConnection performAndWait:] + 144 15 CoreData 0x0000000183a6c35c -[_NSSQLiteStoreMigrator performMigration:] + 184 16 CoreData 0x0000000183a63db0 -[NSSQLiteInPlaceMigrationManager migrateStoreFromURL:type:options:withMappingModel:toDestinationURL:destinationType:destinationOptions:error:] + 1912 17 CoreData 0x00000001839ee814 -[NSMigrationManager migrateStoreFromURL:type:options:withMappingModel:toDestinationURL:destinationType:destinationOptions:error:] + 556 18 CoreData 0x0000000183a5f090 -[NSStoreMigrationPolicy(InternalMethods) migrateStoreAtURL:toURL:storeType:options:withManager:error:] + 324 19 CoreData 0x0000000183a5e3ec -[NSStoreMigrationPolicy migrateStoreAtURL:withManager:metadata:options:error:] + 120 20 CoreData 0x0000000183a5fb08 -[NSStoreMigrationPolicy(InternalMethods) _gatherDataAndPerformMigration:] + 2440 21 CoreData 0x00000001839fc188 __91-[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:]_block_invoke + 4160 22 CoreData 0x0000000183a08630 gutsOfBlockToNSPersistentStoreCoordinatorPerform + 168 23 libdispatch.dylib 0x00000001804fe9a0 _dispatch_client_callout + 16 24 libdispatch.dylib 0x000000018050bee0 _dispatch_barrier_sync_f_invoke + 84 25 CoreData 0x00000001839f7d70 _perform + 200 26 CoreData 0x000000018390d5e4 -[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:] + 388I don't have more details on the crash. Only that it happens for a few users and not all. I have no idea how to reproduce it for a proper fix. The user reported that the app started, was "frozen" for some time and then it crashed. And it keeps doing so.I had a look at the last version of the core-data model since I shipped the app and this file is still the exact same. During development I added 5 more versions in-between but that shouldn't be a problem right? The version shipped in the app before the update is untouched...The changes I made to the model were simply adding some new properties on existing entities. But if auto-migration would fail, it would fail for everybody, right? Not only for a few users?!?So I was hoping somebody here already might had the same issue and a solution on how to fix it. Or at least a way on how to detect the problem without the app crashing. Then I could just recreate the DB for those users...Thanks,Georg
Posted
by
Post not yet marked as solved
3 Replies
3.5k Views
We're seeing a rare issue in the field that I haven't been able to reproduce. The app primarily uses a main queue managed object context, with a couple of other private queue contexts for specialized cases. Those cases do not modify objects that are also modified in the main queue context, so we haven't done anything to specifically handle merge conflicts. We shouldn't have any during normal operation.In at least one case, a user transitions from background to foreground and back to background in a short period of time. One of the things we do when transitioning to inactive state is to save the main queue context. During this save, sometimes it appears that all of the objects loaded in the main queue context will become conflicted. When this happens, the conflicts are very odd:Failed to save: Error Domain=NSCocoaErrorDomain Code=133020 "Could not merge changes." UserInfo={conflictList=( "NSMergeConflict (0x11d8ec540) for NSManagedObject (0x11bf50990) with objectID '0xd00000000f340014 <x-coredata://36EBC17F-A244-4CE0-BB10-C0C5C2C3AFC1/Document/p973>' with oldVersion = 0 and newVersion = 4 and old object snapshot = { ... all attributes are null ... } and new cached row = { ... all attributes have the expected values ... }"I've encountered merge conflicts in the past, and they're due to modifications made in two contexts simultaneously. Here, we aren't modifying simultaneously, the oldVersion value is 0 and the old object snapshot is an empty object (none of the attributes are set to a value).Has anyone else seen this behavior? Is there an explanation for how an object could have an oldVersion = 0?Also, the docs don't provide quite enough detail for me to understand the difference between an "object snapshot" and a "cached row".
Posted
by
Post not yet marked as solved
4 Replies
3.5k Views
Following along with WWDC17 Session 210 - What's new in Core Data:I ticked a couple of string properties on an Entitiy in Core Data UI modeler - Index in Spotlightthen with the instantiated NSManagedObjectModel set an expression to the entity coreSpotlightDisplayNameExpression:if let myEntity = mom.entitiesByName["MyEntity"] { myEntity.coreSpotlightDisplayNameExpression = NSExpression(block: { (object, expressions, dict) -> Any in let displayName = CSLocalizedString(localizedStrings: ["en": "My Item"]) return displayName.localizedString() } }(Don't know if this NSExpression works at all as block not been called as of yet)then subclassed NSCoreDataCoreSpotlightDelegateclass MyCoreDataCoreSpotlightDelegate: NSCoreDataCoreSpotlightDelegate { override func attributeSet(for object: NSManagedObject) -> CSSearchableItemAttributeSet? { guard let attributeSet = super.attributeSet(for: object) else { return nil } if "MyEntity" == object.entity.name { let item = object as! MyEntity attributeSet.displayName = item.itemName attributeSet.contentDescription = item.note } return attributeSet } }(Don't know if this override works at all as not been called as of yet)Setting up Core Data with NSPersistentContainer:let persistentStore = NSPersistentStoreDescription(url: dataStoreURL) persistentStore.setValue("WAL" as NSObject?, forPragmaNamed: "journal_mode") persistentStore.setOption(NSNumber(value: true), forKey:NSPersistentHistoryTrackingKey) let coreSpotlightDelegate = MyCoreDataCoreSpotlightDelegate(forStoreWith:persistentStore, model: persistentContainer.managedObjectModel) persistentStore.setOption(coreSpotlightDelegate, forKey:NSCoreDataCoreSpotlightExporter) persistentContainer.persistentStoreDescriptions = [persistentStore] persistentContainer.loadPersistentStores { storeDescription, error in }I have even added the Entitlement to talk to Core Spotlight 'com.apple.application-identifier = $(TeamIdentifierPrefix)$(CFBundleIdentifier)', just in case.....Unfortunately, this setup results in the main thread being blocked as soon as loadPersistentStores is called. Cpu runs at about 30-40% continuously, disk activity 1 MB/s, memory doesnt seem to increase at all.Pausing gives us a backtrace of:* thread #1, queue = 'NSManagedObjectContext 0x6040003c7530', stop reason = signal SIGSTOP * frame #0: 0x0000000116fe47fe libsystem_kernel.dylib`semaphore_wait_trap + 10 frame #1: 0x0000000116b598cf libdispatch.dylib`_dispatch_sema4_wait + 16 frame #2: 0x0000000116b5a018 libdispatch.dylib`_dispatch_semaphore_wait_slow + 101 frame #3: 0x00000001142d9aeb CoreData`-[NSCoreDataCoreSpotlightDelegate _updateSpotlightClientStateForHistoryTracking:] + 299 frame #4: 0x00000001142d8ea7 CoreData`__73-[NSCoreDataCoreSpotlightDelegate _importObjectsUpdatedSinceTransaction:]_block_invoke + 263 frame #5: 0x00000001140df748 CoreData`developerSubmittedBlockToNSManagedObjectContextPerform + 168 frame #6: 0x0000000116b5933d libdispatch.dylib`_dispatch_client_callout + 8 frame #7: 0x0000000116b60235 libdispatch.dylib`_dispatch_queue_barrier_sync_invoke_and_complete + 392 frame #8: 0x00000001140df64e CoreData`-[NSManagedObjectContext performBlockAndWait:] + 286 frame #9: 0x00000001142d8d3f CoreData`-[NSCoreDataCoreSpotlightDelegate _importObjectsUpdatedSinceTransaction:] + 287 frame #10: 0x00000001142da05a CoreData`-[NSCoreDataCoreSpotlightDelegate _catchUpToCurrentTransaction] + 218 frame #11: 0x000000011408a2d9 CoreData`-[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:] + 969 frame #12: 0x0000000114199f50 CoreData`-[NSPersistentStoreCoordinator _doAddPersistentStoreWithDescription:privateCopy:completionHandler:] + 336 frame #13: 0x000000011419a361 CoreData`-[NSPersistentStoreCoordinator addPersistentStoreWithDescription:completionHandler:] + 177 frame #14: 0x000000011414ee7c CoreData`-[NSPersistentContainer loadPersistentStoresWithCompletionHandler:] + 668 frame #15: 0x000000010df48093 MyNewApp`SharedStoreHelper.init(storeName="0E4D1B65-58DB-464D-B64C-39D6C547F2F2", shareOwner="__defaultOwner__", coreSpotlightDelegateClass=MyNewApp.MyCoreDataCoreSpotlightDelegate, completion=0x000000010e06b360 MyNewApp`partial apply forwarder for closure #2 (Swift.Bool, MyNewApp.SharedStoreHelper) -> () in MyNewApp.ReloadStoresOperation.(reloadStores in _05B52F3B437462E7EAD7CB8BA8EFB1A6)(MyNewApp.SharedStoreHelper.Type, Swift.Optional<(Swift.Bool, Swift.Optional<MyNewApp.ArrayChanges>) -> ()>) -> () at ReloadStoresOperation.swift) at SharedStoreHelper.swift:101 frame #16: 0x000000010e0b708d MyNewApp`MyNewAppSharedStoreDataManager.init(storeName="0E4D1B65-58DB-464D-B64C-39D6C547F2F2", shareOwner="__defaultOwner__", coreSpotlightDelegateClass=MyNewApp.MyCoreDataCoreSpotlightDelegate, completion=0x000000010e06b360 MyNewApp`partial apply forwarder for closure #2 (Swift.Bool, MyNewApp.SharedStoreHelper) -> () in MyNewApp.ReloadStoresOperation.(reloadStores in _05B52F3B437462E7EAD7CB8BA8EFB1A6)(MyNewApp.SharedStoreHelper.Type, Swift.Optional<(Swift.Bool, Swift.Optional<MyNewApp.ArrayChanges>) -> ()>) -> () at ReloadStoresOperation.swift) at MyNewAppSharedStoreDataManager.swift:0 frame #17: 0x000000010e0b6df1 MyNewApp`MyNewAppSharedStoreDataManager.__allocating_init(storeName:shareOwner:coreSpotlightDelegateClass:completion:) at MyNewAppSharedStoreDataManager.swift:0 frame #18: 0x000000010e06802b MyNewApp`ReloadStoresOperation.reloadStores(storeType=MyNewApp.MyNewAppSharedStoreDataManager, completionHandler=0x000000010defda10 MyNewApp`partial apply forwarder for closure #1 (Swift.Bool, Swift.Optional<MyNewApp.ArrayChanges>) -> () in closure #1 (__ObjC.NSPersistentStoreDescription, Swift.Optional<Swift.Error>) -> () in MyNewApp.MultiStoreManager.init(MyNewApp.SharedStoreHelper.Type, coreSpotlightDelegateClass: Swift.Optional<__ObjC.NSCoreDataCoreSpotlightDelegate.Type>, (Swift.Bool, MyNewApp.MultiStoreManager) -> ()) -> MyNewApp.MultiStoreManager at MultiStoreManager.swift, self=0x0000600000675140) at ReloadStoresOperation.swift:49 frame #19: 0x000000010e0673f3 MyNewApp`ReloadStoresOperation.beginAsynchronousTask(self=0x0000600000675140) at ReloadStoresOperation.swift:24 frame #20: 0x000000010e067424 MyNewApp`@objc ReloadStoresOperation.beginAsynchronousTask() at ReloadStoresOperation.swift:0 frame #21: 0x0000000112a85ee8 Ensembles`-[CDEAsynchronousOperation start](self=0x0000600000675140, _cmd="start") at CDEAsynchronousOperation.m:50 frame #22: 0x0000000112bb91e8 Foundation`__NSThreadPerformPerform + 334 frame #23: 0x0000000114669101 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 frame #24: 0x0000000114708f71 CoreFoundation`__CFRunLoopDoSource0 + 81 frame #25: 0x000000011464da6b CoreFoundation`__CFRunLoopDoSources0 + 267 frame #26: 0x000000011464cfff CoreFoundation`__CFRunLoopRun + 1279 frame #27: 0x000000011464c889 CoreFoundation`CFRunLoopRunSpecific + 409 frame #28: 0x00000001187539c6 GraphicsServices`GSEventRunModal + 62 frame #29: 0x000000011060c5d6 UIKit`UIApplicationMain + 159 frame #30: 0x000000010e07ee27 MyNewApp`main at AppDelegate.swift:18 frame #31: 0x0000000116bd5d81 libdyld.dylib`start + 1There is almost zero information about how to set this up (apple documentation or Stackoverflow etc.), other than the WWDC17 210 session. Does anyone have any ideas what to try next? or even if this is meant to work at all?Many thanks in advance
Posted
by
Post not yet marked as solved
2 Replies
2.8k Views
I am trying to set up a simple core data app. But after I create the NSManagedObject subclasses from the Editor menu I get numerous errors that I do not understand.<unknown>:0: error: filename "Fields2+CoreDataClass.swift" used twice: '/Current Projects/Stages/Stages/CoreData/Fields2+CoreDataClass.swift' and '/Users/me/Library/Developer/Xcode/DerivedData/Stages-bvmokbzazpxlmwaxrpiatcooijvt/Build/Intermediates.noindex/Stages.build/Debug-iphoneos/Stages.build/DerivedSources/CoreDataGenerated/Stages/Fields2+CoreDataClass.swift'<unknown>:0: note: filenames are used to distinguish private declarations with the same nameCommand /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1In the extension for Fields2 I get'Fields2' is ambiguous for type lookup in this contextthen I get@NSManaged only allowed on an instance property or method for all of the properties in Fields2Is this a bug? Or am I doing something wrong? What is going on and how do I fix it?
Posted
by
Post not yet marked as solved
12 Replies
6.5k Views
Anybody facing issues with saving binary data with "Allows external storage" checked in your property? I am just now facing some customer queries why their saved images are disappearing after a while in my app. This used to work just fine in iOS 11. I have been debugging this issue with simMagnifier tool for viewing the Core Data content as well as just checking the contents of iOS 12 simulator directory on macOS.Now I am seeing in simulator that when I set the image property and save the context, image file gets written to _EXTERNAL_DATA -directory but the image field in Core Data stays nil. My app shows the image cause it is saved to managed object context in memory. But once app gets killed and user reopens, the image is not there - cause apparently it was not saved properly in the first place. What on earth is going on and can I do something to make this work or is this just a serious bug on iOS 12?
Posted
by
Post not yet marked as solved
0 Replies
603 Views
I am using the NSBatchDeleteRequest on a background thread to delete thousands of objects from a SQLite Core Data store. My observation is that in my case it requires about 20 seconds to delete 1000 objects. Is this too slow in comparison to what it should do ?I tried to distribute the work over several threads with no improvement even when using different NSPersistentStoreCoordinators to allow parallel write access to the store. Is there another way to improve this ?
Posted
by
Post not yet marked as solved
2 Replies
1.2k Views
Hello:I have been struggling with this small piece of code foe days. Every time I resolve one problem with it, another one pops up:I seem to have resolved the problem of "Expected Pattern" but now I have the problem "Cannot call value of non-function type '[String]'Here is the code:var name = [String]() override func viewDidLoad() { super.viewDidLoad() let persistentContainer = NSPersistentContainer(name: "No_Regrets") persistentContainer.loadPersistentStores { (_, error) in if let error = error { fatalError("Failed to load Core Data stack: \(error)") } } // Creates a task with a new background context created on the fly persistentContainer.performBackgroundTask { (context) in //iterates the array let Gains = [self.gain1, self.gain2, self.gain3, self.gain4] Gains.forEach {_ in // Creates a new entry inside the context `context` and assign the array element `name` to the dog's name let gain1 = Gains(context: context) //Cannot call value of non-function type '[String]' gain1.name = name let gain2 = Gains(context: context) //Cannot call value of non-function type '[String]' gain2.name = name let gain3 = Gains(context: context) //Cannot call value of non-function type '[String]' gain3.name = name let gain4 = Gains(context: context) //Cannot call value of non-function type '[String]' gain4.name = name } do { // Saves the entries created in the `forEach` try context.save() } catch { fatalError("Failure to save context: \(error)") } }
Posted
by
Post not yet marked as solved
1 Replies
724 Views
Ive setup a tableview controller and am using it for a weight tracking list w/ coredata to save all of the entries made. While everything works as far as adding entries and displaying them while the app is open, it's not displaying those entries on the next app load. So either my save or load method is not doing its job. I appreciate the help as im relatively new to swift coding.import UIKit import CoreData class TodoViewController: UITableViewController { var items = [Items]() let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext var selectedCategory: Items?{ didSet{ loadItems() } } override func viewDidLoad() { super.viewDidLoad() } //MARK: Table View Datasource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Item", for: indexPath) let item = items[indexPath.row] cell.textLabel?.text = item.name cell.accessoryType = item.completed ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) items[indexPath.row].completed = !items[indexPath.row].completed saveItems() } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == .delete){ let item = items[indexPath.row] items.remove(at: indexPath.row) context.delete(item) do{ try context.save() }catch{ print("Error deleting item with \(error)") } tableView.deleteRows(at: [indexPath], with: .automatic) } } @IBAction func addButtonPressed(_ sender: UIBarButtonItem) { var textField = UITextField() let alert = UIAlertController(title: "Add New Weight", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Save", style: .default) { (action) in let newItem = Items(context: self.context) newItem.name = textField.text! self.items.append(newItem) self.saveItems() } alert.addAction(action) alert.addTextField { (field) in textField = field textField.placeholder = "Add Weight" } present(alert, animated: true, completion: nil) } func saveItems(){ do{ try context.save() }catch{ print("Error Saving item with \(error)") } self.tableView.reloadData() } func loadItems(){ let request: NSFetchRequest = Items.fetchRequest() do{ items = try context.fetch(request) }catch{ print("Error fetching data from context \(error)") } tableView.reloadData() } }
Posted
by
Post not yet marked as solved
1 Replies
303 Views
Today I've investigated migration error. According to my investigations model with preserving after deletion fields would get incorrect hash calculation. That's why custom mapping model would not applied.In `-com.apple.CoreData.MigrationDebug 1` logs the next entry happens: 'CoreData: annotation: (migration) mismatched and destination hashes for mapping model MappingModel.cdm'.My mapping model was regenerated several times on different machines to get rid of potential local issues.Sample code: https://github.com/OdNairy/CloudKitError-FB6713955.gitFeedback ID: FB6713955
Posted
by
Post not yet marked as solved
20 Replies
10k Views
I'm running into trouble setting up sync using NSPersistentCloudKitContainer on an existing app. The app doesn't seem to sync data that was added to Core Data prior the app's iOS 13 update. For instance:1. I install an existing, pre-iOS 13, version of the app and create several records that are stored in Core Data.2. Over that existing install, I install the updated version that uses NSPersistentCloudKitContainer and create some additional new records.3. I install the same new version on a second device.Results: Records created in step 1 don't appear on the second device, but records created in step 2 do.Is there a step I'm missing in order to get existing data to sync? I'm wondering if this has something to do with the persistent history token, but I'm unsure how to tell NSPersistentCloudKitContainer it should "start over" on first launch.
Posted
by
Post not yet marked as solved
1 Replies
673 Views
what happens ?0 CoreFoundation 0x00000001d1b55294 + 252 1 libobjc.A.dylib 0x00000001d0d2f9f8 objc_exception_throw + 56 2 CoreData 0x00000001d4714694 + 0 3 CoreData 0x00000001d4714868 + 208 4 CoreData 0x00000001d4714af8 + 608 5 CoreData 0x00000001d45aad14 + 240 6 CoreData 0x00000001d45ab99c + 844 7 CoreData 0x00000001d45ab9c8 + 888 8 CoreData 0x00000001d45ac81c + 1592 9 XMPPFramework 0x00000001056d7920 -[XMPPCoreDataStorage save] + 304 10 XMPPFramework 0x00000001056d7e98 __37-[XMPPCoreDataStorage scheduleBlock:]_block_invoke + 76 11 libdispatch.dylib 0x00000001d1594a38 + 24 12 libdispatch.dylib 0x00000001d15957d4 + 16 13 libdispatch.dylib 0x00000001d1570dec + 548 14 libdispatch.dylib 0x00000001d157192c + 408 15 libdispatch.dylib 0x00000001d1579e08 + 584 16 libsystem_pthread.dylib 0x00000001d1775114 _pthread_wqthread + 304 17 libsystem_pthread.dylib 0x00000001d1777cd4 start_wqthread + 4
Posted
by
glx
Post not yet marked as solved
6 Replies
5.7k Views
Dear everyone,I am relatively new to Core Data and I was trying to create a small app in Swift UI to display a list of elements and being able to add new ones.I created an entity (Codegen: Manual/None) with the following fields:- city: String- country: String- createdAt: Date- date: Date- id: UUID- summary: StringAn I created the equivalent class:public class EventItems: NSManagedObject, Identifiable { @NSManaged public var id: UUID @NSManaged public var city: String @NSManaged public var country: String @NSManaged public var date: Date @NSManaged public var createdAt: Date @NSManaged public var summary: String }And the following extensionextension EventItems { static func getAllItems() -> NSFetchRequest<EventItems> { let request: NSFetchRequest<EventItems> = NSFetchRequest<EventItems>(entityName: "EventItems") request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)] return request } }In a SwiftUI view, I set the Environement and then have a button to save a new element:@Environment(\.managedObjectContext) var managedObjectContextButton(action: { let eventItem:EventItems = EventItems(context: self.managedObjectContext) eventItem.id = UUID() eventItem.city = self.city eventItem.country = self.country eventItem.date = self.date eventItem.createdAt = Date() eventItem.summary = self.summary do { try self.managedObjectContext.save() } catch { print(error) } }) { Text("Save") }In my View to add a new element to the entity, when I press the save button, the application crashes with the following error:2019-10-20 20:50:04.209071+0200 EventLogger[14093:945375] [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'EventLogger.EventItems' so +entity is confused. Have you loaded your NSManagedObjectModel yet ?CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'EventLogger.EventItems' so +entity is confused. Have you loaded your NSManagedObjectModel yet ?2019-10-20 20:50:04.209361+0200 EventLogger[14093:945375] [error] error: +[EventLogger.EventItems entity] Failed to find a unique match for an NSEntityDescription to a managed object subclassCoreData: error: +[EventLogger.EventItems entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass2019-10-20 20:50:04.219017+0200 EventLogger[14093:945375] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'EventLogger.EventItems' must have a valid NSEntityDescription.'Thanks for your help 🙂
Posted
by
Post not yet marked as solved
3 Replies
1.9k Views
I have a SwiftUI app sitting on top of a CoreData + CloudKit stack. If I have the app running on multiple devices, a change on one device will not always be reflected on the others. However, restarting the app on the other device will pick up the change. For example:Device A and Device B both have the app running. Device B has it in the background.Device A changes Record 1. Device B returns to the foreground, but does not see the change to Record 1Kill the app on Device B, relaunch, and it sees the changeIt seems that the cloudkit process isn't always getting change notifications from iCloud (note that this happens on actual devices, not just the sim). If we could tell the container "Hey, I just retuned to the foreground, maybe check to see if anything has changed?", that would, I think, fix the problem. I can't tear down my CoreData stack without rebuilding the entire app (since the main thread context is pushed down into SwiftUI).Is there a way to force this update?Thanks!Ben
Posted
by
Post not yet marked as solved
1 Replies
1k Views
Hi,How can I use a Core Data's Fetch Index in my query predicate?I saw the announcement talk (from WWDC'17) and they appear to be using indexed:by:(indexName, propertyName) , I tried that but I just get Unable to parse the format string "indexed:by:(myIndexName, myPropertyName)”Thank you in advance for your help.
Posted
by
Post marked as solved
4 Replies
1.7k Views
I'm getting the following error messages:CoreData: annotation: Failed to load optimized model at path '/var/containers/Bundle/Application/0E3DF5FB-DA57-4A63-98FE-59E2961C6F50/Routes.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileProto.omo'2020-01-11 17:19:50.885657-0600 Routes[1913:394464] [error] fault: 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.. . .CoreData: warning: Property 'value' on Entity 'GMSCacheProperty' is using nil or an insecure NSValueTransformer. Please switch to using "NSSecureUnarchiveFromData" or a subclass of NSSecureUnarchiveFromDataTransformer instead.. . .2020-01-11 17:20:08.491131-0600 Routes[1913:394093] Can't end BackgroundTask: no background task exists with identifier 13 (0xd), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.I don't know what the problem is because I am not using any CoreData Attributes of type Transformable nor is there any code in my project about anything transformable. I have searched with Google for this error, but have not found a solution that works.
Posted
by
Post not yet marked as solved
3 Replies
1.2k Views
So when I turn off NSPersistentHistoryTrackingKey I get this error then the App Crashes:error: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store at ...CoreData: error: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store at...error: (8) attempt to write a readonly databaseCoreData: error: (8) attempt to write a readonly databaseFile is in Read Only mode due to Persistent History being detected but NSPersistentHistoryTrackingKey was not includedHow do I turn it off without having this happen?Ray
Posted
by
Post not yet marked as solved
1 Replies
793 Views
In Xcode you can setup constraints for a Core Data entity with the Data Model Inspector in the Constraints area. For every constraint added via + it set the example constraint "comma,separated,properties". You can configure more than one such constraint.In the model file it looks like this:<entity>… <uniquenessConstraints> <uniquenessConstraint> <constraint value="parent"/> <constraint value="title"/> <constraint value="birthday"/> </uniquenessConstraint> <uniquenessConstraint> <constraint value="firstName"/> <constraint value="lastName"/> </uniquenessConstraint> </uniquenessConstraints></entity>Question: What it the logic? How to read this? Is it AND or OR inside a constraint? Is it AND or OR between multiple constraints?While testing i came to this conclusion:Every constraint says: All attributes in this constraint must have the same value for two ManagedObjects to matchOnly one constraint is required to match in order for two ManagedObjects to matchThis means:The attributes (constraint values) must all match per constraint (AND)At least one constraint must match (OR)Or with an example: Two ManagedObjects would match, if they have (the same parent AND title AND birthday) OR (the same firstName AND lastName).Is this correct?In this developer video https://developer.apple.com/videos/play/wwdc2015/220/?time=821they're importing recipe data from various sources and configure one constraint to avoid duplicates: "source,externlID". This looks like source and externlID must match both (AND) to identify a duplicate. This would support my interpretation for constraints above.
Posted
by