We cannot use NSFetchRequest without providing NSSortDescriptor(s). All i want to do is fetch the results and show them in the order in which they were created. Is there a built-in way to do that?, or will i have to create a new "auto-increment" field? (which goes against everything CoreData stands for, in my opinion).
Core Data does not guarantee anything about order. You don't have to make an "auto-increment" field; however, you can make an appropriate attribute. Since you obviously care about the date something was created, you should add a dateCreated attribute to your data object. Then, sort by that.
You can easily set that in the managed object's didAwakeFromInsert
method.
It sounds like you're thinking of Core Data in terms of tables and expect that there should be an automatic ordering just like the row number of table provides. However, Core Data does not use tables, rows or any other fixed, linear data structure.
There is no built-in order for fetches because each fetch request is highly specific to the needs of the view it helps populate. NSFetchRequest
requires a sort descriptor because it returns an array and requires a sort descriptor to turn the unordered managed objects within the object graph into an ordered array.
There is no built-in order for managed objects in the object graph in general because each data model has different criteria for structuring the data. E.g for most models, the temporal sequences in which objects are inserted is irrelevant. Why build in a timestamp into every managed object that every Core Data app everywhere must use when it will only be needed in a tiny minority of cases?
If the temporal sequences is an important part of your model's logical relationships i.e. it reflects the real objects, events or conditions that the data model simulates then, as Jason Coco suggested, you should add a timestamp attribute to the entity itself such that the entities objects will model the time of their own creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With