'Core Data: Sorting by date not working properly

I'm trying to sort my Core Data items by date. When creating a new item it would sort correctly by date added (newest to oldest) but after creating more than 3 it would stop being in order and would display randomly in the list.

@objc(MyBookmark)
public class MyBookmark: NSManagedObject, BaseModel {
    static var all: NSFetchRequest<MyBookmark> {
        
        
        
        let request: NSFetchRequest<MyBookmark> = MyBookmark.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(keyPath: \MyBookmark.timestamp, ascending: true)]
        return request
           
    }
    
}


extension MyBookmark {

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

    @NSManaged public var name: String?
    @NSManaged public var url: String?
    @NSManaged public var timestamp: Date

}

extension MyBookmark : Identifiable {

}

I tested out sorting 'MyBookmark' by name and it works perfectly. The 'timestamp' attribute wasn't there before and i just added it to the model.

enter image description here

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 url: String {
        myBM.url ?? ""
    }
    
    var timestamp: Date {
        myBM.timestamp ?? Date()
    }

   
}

ContentView

@ObservedObject var vm : MyBookmarksViewModel

              ForEach(vm.myBookmarks) { myBookmark in   
  
                    Text(myBookmark.name)
                    Text(myBookmark.date, itemFormatter)   
                    
                          }
    
    
               private let itemFormatter: DateFormatter = {
               let formatter = DateFormatter()
               formatter.dateStyle = .short
               formatter.timeStyle = .medium
               return formatter
                }()

*Update

The timestamps in the Content View of all items are exactly the same. When adding a new item, the older items update to the same time as the new one.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source