Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

42 рядки
1.6 KiB

  1. import SwiftUI
  2. import CoreData
  3. class CollectionListModel: NSObject, ObservableObject {
  4. @Published var list: [WFACollection] = []
  5. private let collectionsController: NSFetchedResultsController<WFACollection>
  6. init(managedObjectContext: NSManagedObjectContext) {
  7. collectionsController = NSFetchedResultsController(fetchRequest: WFACollection.collectionsFetchRequest,
  8. managedObjectContext: managedObjectContext,
  9. sectionNameKeyPath: nil,
  10. cacheName: nil)
  11. super.init()
  12. collectionsController.delegate = self
  13. do {
  14. try collectionsController.performFetch()
  15. list = collectionsController.fetchedObjects ?? []
  16. } catch {
  17. // FIXME: Errors cannot be thrown out of the CollectionListView property initializer
  18. fatalError(LocalStoreError.couldNotFetchCollections.localizedDescription)
  19. }
  20. }
  21. }
  22. extension CollectionListModel: NSFetchedResultsControllerDelegate {
  23. func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  24. guard let collections = controller.fetchedObjects as? [WFACollection] else { return }
  25. self.list = collections
  26. }
  27. }
  28. extension WFACollection {
  29. static var collectionsFetchRequest: NSFetchRequest<WFACollection> {
  30. let request: NSFetchRequest<WFACollection> = WFACollection.createFetchRequest()
  31. request.sortDescriptors = [NSSortDescriptor(keyPath: \WFACollection.title, ascending: true)]
  32. return request
  33. }
  34. }