I'm trying to reorder items in a list that's stored with CoreData using this answer. This is a macOS swiftUI App using MVVM layout.
Here's the ContentView
@ObservedObject var vm : MyBookmarksViewModel
ForEach(vm.myBookmarks) { myBookmark in
Text(myBookmark.name)
...................
}
.onMove(perform: vm.reorderItems(from:to:))
I'm getting the 'Cannot assign to property: 'order' is a get-only property' error inside the reorderItems function below next to myBookmarks[ reserveIndex ].order
MyBookmarksViewModel
@Published var myBookmarks = [MyBookmarkViewModel]()
let fetchedResultsController: NSFetchedResultsController<MyBookmark>
private var context: NSManagedObjectContext
init(context: NSManagedObjectContext){
self.context = context
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: MyBookmark.all , managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
super.init()
fetchedResultsController.delegate = self
}
func reorderItems( from source: IndexSet, to destination: Int)
{
// Make an array of items from fetched results
// change the order of the items in the array
myBookmarks.move(fromOffsets: source, toOffset: destination )
// update the userOrder attribute in revisedItems to
// persist the new order. This is done in reverse order
// to minimize changes to the indices.
for reserveIndex in stride( from: myBookmarks.count - 1,
through: 0,
by: -1 )
{
myBookmarks[ reserveIndex ].order = // this is where i get an error
Int64(reserveIndex)
}
}
MyBookmarkViewModel
struct MyBookmarkViewModel: Identifiable, Hashable {
init(myBM: MyBookmark) {
self.myBM = myBM
}
private let myBM: MyBookmark
var id: NSManagedObjectID {
myBM.objectID
}
var name: String {
myBM.name ?? ""
}
var order: Int64 {
myBM.order
}
}
MyBookmark
@objc(MyBookmark)
public class MyBookmark: NSManagedObject, BaseModel {
static var all: NSFetchRequest<MyBookmark> {
let request: NSFetchRequest<MyBookmark> = MyBookmark.fetchRequest()
let sort = NSSortDescriptor(keyPath: \MyBookmark.order, ascending: true)
request.sortDescriptors = [sort]
return request
}
}
extension MyBookmark {
@nonobjc public class func fetchRequest() -> NSFetchRequest<MyBookmark> {
return NSFetchRequest<MyBookmark>(entityName: "MyBookmark")
}
@NSManaged public var name: String?
@NSManaged public var order: Int64
}
extension MyBookmark : Identifiable {
}
CodePudding user response:
In MyBookmarkViewModel
order
is a computed read-only property.
If you want to set it you need a set {}
branch
var order: Int64 {
get { myBM.order }
set { myBM.order = newValue }
}