2

I´m banging my head against the desk about the following problem. I have a nested DataStore (for convenience), integrated into a view via @EnvironmentObject. If I change something in the DataStore (eg. putting a new object inside - which works fine-), the UI does not update.

In the console, I also get the results of the print("Object Changed"), caused by a change in the fetched results. But the UI only updates after I restart the app. Whats wrong here?

Thanks a lot in advance!

My Test Code looks like this:

The DataStore:

import Foundation
import Combine

class DataStore : ObservableObject{
    @Published var documents    = DocumentStore()
    @Published var attachments  = AttachmentStore()
}

The Attachment Store

//
//  AttachmentStore.swift

import SwiftUI
import Combine
import CoreData

class AttachmentStore: NSObject, ObservableObject {


    // MARK: Private Properties
     let persistenceManager = PersistenceManager()

    private lazy var fetchedResultsController: NSFetchedResultsController<ManagedAttachment> = {
        let fetchRequest: NSFetchRequest<ManagedAttachment> = ManagedAttachment.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: false)]

        let fetchedResultsController = NSFetchedResultsController(
            fetchRequest: fetchRequest,
            managedObjectContext: self.persistenceManager.managedObjectContext,
            sectionNameKeyPath: nil,
            cacheName: nil)
        fetchedResultsController.delegate = self
        return fetchedResultsController
    }()

    private var attachment: [ManagedAttachment] {
        return fetchedResultsController.fetchedObjects ?? []
    }

    // MARK: Public Properties

    @Published var Items : [ManagedAttachment] = []

    public var allItems: [ManagedAttachment] {
        return self.attachment.filter {$0 == $0}
       }

    func setup(){
        self.Items = allItems
    }
    // MARK: Object Lifecycle

    override init() {
        super.init()
        fetchDocuments()
        setup()
    }

    // MARK: Public Methods

    public func allAttachments(for id: UUID) -> [ManagedAttachment]
    {
        let attachments = self.allItems.filter {$0.parentID == id}
        return attachments
    }

    public func create(attachment: Attachment) {
        ManagedAttachment.create(object: attachment, in: self.persistenceManager.managedObjectContext)
         saveChanges()
     }

    public func delete(attachment: ManagedAttachment){
        persistenceManager.managedObjectContext.delete(attachment)
        self.saveChanges()
    }

    public func update(){
        self.saveChanges()
    }


    // MARK: Private Methods

    private func fetchDocuments() {
        do {
            try fetchedResultsController.performFetch()
            dump(fetchedResultsController.sections)
        } catch {
            fatalError()
        }
    }

    private func saveChanges() {
        guard persistenceManager.managedObjectContext.hasChanges else { return }
        do {
            try persistenceManager.managedObjectContext.save()
            self.objectWillChange.send()
            print("Object Changed")
        } catch { fatalError() }
    }
}


extension AttachmentStore: NSFetchedResultsControllerDelegate {
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        self.objectWillChange.send()
        print("Object Changed")
    }
}


The TestView

import SwiftUI

struct TestView: View {
    @EnvironmentObject var data : DataStore

    var body: some View {
        VStack{
            Button(action: {
                self.data.attachments.create(attachment: Attachment(url: "Test"))
            }
            ) {
                Text("Add")
            }
            // Print the Items in the DataStore
            ForEach(data.attachments.Items, id:\.self){Item in
                Text(Item.url).font(.caption)
            }
        }

    }
}
sTOOs
  • 564
  • 1
  • 5
  • 9
  • 1
    See this answer: https://stackoverflow.com/a/58917498/6570854 – ribilynn Nov 30 '19 at 04:39
  • What exactly isn't working? I don't see you mutating `Items` anywhere other than `setup()` – Gil Birman Dec 01 '19 at 01:39
  • @ribilynn: Thank you very much - I fixed it. My problem was that I send a willChange from the attachmentStore - but not from the datastore object. Thanks a lot! – sTOOs Dec 02 '19 at 11:34

1 Answers1

2

Ok, my problem here was that I send a willChange from the attachment store- but not from the data store, so it did not update. So the solution was to manually call dataStore.objectWillChange.send(). Thank you!

sTOOs
  • 564
  • 1
  • 5
  • 9