I have a fully working core data model, but when I return the data using a fetch request, it’s in a seemingly random order. What is the best way to sort this data? Is it to use another table in the Core Data model, and ‘query’ the first? Or would it be to pull down the data into an array, and sort it that way?
I’m not too sure how to do either of these, which is the reason that I am asking this question.
Your question is quite general but I’ll try to give you some hints.
When you use
NSFetchRequestclass you can specify sort descriptors.From Apple doc:
Here you can find a simple example within Core Data Snippets doc
Where
<#Entity name#> is the name of the entity you want to retrieve, e.g.
Manager.<#Sort key#> is the name of the key the request will use to order, e.g.
nameis an attribute ofManagerentity.So, in my example:
Since
setSortDescriptors:sets an array of sort descriptors, you can specify multiple keys against you want to order. e.g. specify to order againstnameandsalary. The sort descriptors are applied in the order in which they appear in the sortDescriptors array. So, in my example, first bynameand then bysalary.So, in my example, it could become
Hope that helps.
Edit
Since
fetchedObjectscontainsNSManagedObject(I suppose you did not change the result type of your request) you need to iterate like the following:So, you need to access attributes or relationships through Key Value Coding. To make your life easier you could think to create
NSManagedObjectsubclasses for the entities you created like organising-core-data-for-ios.