NSFetchRequest without sort descriptors

混江龙づ霸主 提交于 2019-12-07 03:32:29

问题


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).


回答1:


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.




回答2:


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.




回答3:


[[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.



来源:https://stackoverflow.com/questions/3397667/nsfetchrequest-without-sort-descriptors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!