SwiftUI How to get changes of computed Property of NSManagedObject subclass

Viewed 207

I am using a List to display a CoreData one-to-many relationship models. The list displayed the computed property. When the NSManagedObject was changed, the computed property doesn't know about it.

Let's say People has many Books. Like the code below:

People+CoreDataProperties.swift

  extension People {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<Contract> {
        return NSFetchRequest<People>(entityName: "People")
    }

    @NSManaged public var peopleID: String?
    @NSManaged public var name: String?
    @NSManaged public var books: Set<Book>?
    @NSManaged public var bookOrders: [String]

   }

The bookOrders is the ordered id of the books.

BookListView.swift

struct BookListView: View {
   @state var people: People //this is from @FetchRequest
   
   List {
       ForEach(people.sortedBooks.indices, id:\.self) { index in
            BookRowView(bookListItem: viewModel.books[index])
       }
   }
    
}

Here is the extension of People:

extension People {
    var sortedBooks: [Book] {
    
    
    let contractMapping = books.reduce(into: [String: Book]()) { (result, book) in
        result[book.bookID] = book
    }
    return bookOrders.map {
        contractMapping[$0]
    }.compactMap { $0 }

}

So when I reorder the books, which say update the bookOrders or there's a background request update of adding the new books then how can I notify BookListView update the view?

1 Answers

Inside the BookListView declare your People as ObservedObject

struct BookListView: View {
   @ObservedObject var people: People // << now View updates for any changes here
Related