Sorting a Table View of Core Data Records
In my previous post, I detailed the steps needed to bind a view-based table view to a Core Data entity. That post is missing one thing: sorting, which I’m going to cover now.
Add an Ordering Attribute to the Entity #
Core Data does not have built-in support for sorting records. If you want a collection of entities sorted, you must add an attribute to the entity that stores its position in the collection.
Write Code to Create Sort Descriptors #
To sort the table view you first need to bind the array controller’s Sort Descriptors binding. But the array controller needs something to bind to. You must write code to create an array of sort descriptors, NSSortDescriptor, which you will later bind to the array controller. Supply the name of your entity’s ordering attribute as the sort descriptor’s key. The following code shows how to create the sort descriptors in Swift:
func chaptersSortDescriptors() -> [NSSortDescriptor!] {
return [NSSortDescriptor(key: "order", ascending: true)]
}
My entity attribute is named order. Substitute the name of your ordering attribute in your code. You can also use a different method name than chaptersSortDescriptors.
I’m writing a document-based application so I put my sort descriptors method in my NSPersistentDocument subclass. I have not tried this with a shoebox (non-document-based) application. My best guess is you would place the sort descriptors method in your AppDelegate file.
Bind the Array Controller’s Sort Descriptors #
Now it’s time to bind the array controller’s Sort Descriptors binding to the method you wrote that creates the array of sort descriptors.
- Select the array controller from the object list in Interface Builder.
- Open the bindings inspector.
- Click the disclosure triangle next to the Sort Descriptors binding.
- Select the Bind to checkbox.
- Choose File’s Owner from the menu.
- In the Model Key Path text field, enter the name of the method you wrote that creates the sort descriptors.
For Step 5, I’m not sure if you bind to File’s Owner for a shoebox application. You many need to bind to the application instead of File’s Owner.
Bind the Table View’s Sort Descriptors #
The final step is to bind the table view’s Sort Descriptors binding to the array controller’s sort descriptors.
- Select the table view from the object list in Interface Builder.
- Open the bindings inspector.
- Click the disclosure triangle next to the Sort Descriptors binding.
- Select the Bind to checkbox.
- Choose the array controller from the menu.
- In the Controller Key text field, enter
sortDescriptors.