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-incr开发者_如何转开发ement" 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.
[[NSSortDescriptor alloc] initWithKey:@"" ascending:NO];
In my project, I use NSFetchRequest to fetch a list, and all objects in the list have a property which have the same value. so we use that property's name of the "initWithKey:" . It work well.
精彩评论