Binding a View-Based Table View to a Core Data Entity
My main reason for writing this post is to have a reference for myself in case I need to bind a view-based table in the future. If this post helps anyone else, that’s a bonus.
Set up the Array Controller #
The first step is to create an array controller and configure it to control a Core Data entity.
- Add an array controller to the xib file.
- Select the array controller from the object list and open Interface Builder’s attributes inspector.
- Choose Entity Name from the Mode menu.
- Enter your entity name in the Entity Name text field.
- Select the Prepares Content checkbox.
Bind the Array Controller to the Managed Object Context #
After setting up the array controller, you must bind it to your Core Data managed object context.
- Open the bindings inspector.
- Click the disclosure triangle next to the Managed Object Context binding.
- Select the Bind to checkbox.
- Choose File’s Owner from the menu.
- In the Model Key Path text field, enter
managedObjectContext.
Bind the Table View #
The table view needs data to display. Bind the table view to the array controller to get the data.
- Select the table view from the object list.
- Open the bindings inspector.
- Click the disclosure triangle next to the Content binding.
- Select the Bind to checkbox.
- Choose the array controller from the menu.
- In the Controller Key text field, enter
arrangedObjects.
If you have problems with the table view selection, use the table column’s Value binding instead of the table view’s Content binding. In the code I’m working on, I have a table view and a text view. Selecting an item from the table view fills the text view with the item’s contents. When I used the table view’s Content binding, the text view’s contents didn’t change when I selected an item in the table view. Using the table column’s Value binding fixed the problem.
Bind the Table View Cell #
View-based table views require you to bind the table view cell to display something in the table view.
- Select the table view cell from the object list. You may find it easier to use the jump bar to locate the table view cell.
- Open the bindings inspector.
- Click the disclosure triangle next to the Value binding.
- Select the Bind to checkbox.
- Choose Table Cell View from the menu.
- In the Model Key Path text field, enter
objectValue.attribute, whereattributeis the attribute in your Core Data entity that you want to show in the table view.