Search code examples
core-datauitableviewuisplitviewcontrollerone-to-many

How can I use SplitView having TableViewControllers in Master and Detail parts


I am trying to use SplitView in order to show the information about employees. There is a list of departments in the Master part. The list of employers working in the chosen department needs to be shown in the Detail when clicking on the department. I am using CoreData with two Entities: "Department" and "Employee" that are connected with “to-many” relation. How should I do it?

Thanks


Solution

  • This is a simplified overview, since you asked a very broad question.

    1. Create a UITableViewController subclass to be your Master view. It should have a property of type NSManagedObjectContext, and it should handle fetching and displaying the departments. (You could fetch them in loadView, or you could use an NSFetchedResultsController…)

    2. Create another UITableViewController subclass to be your detail view. Give it a property of type NSManagedObjectContext, and also a property of type Department. Make it display the employees for that department. You'll want to make it reload its data whenever the department property changes.

    3. Add a property to your master view controller, to refer to the detail view controller (so a property of type EmployeeViewController, or whatever you called it). Then in tableView:didSelectRowAtIndexPath: in your master view controller, set self.employeeViewController.department = <selected department>.

    4. Create the split view controller. If this is the top level view of your application, you'll want to create it in your app delegate, otherwise create it in the view controller that pushes it to the stack. Here's how to do it (in pseudocode):

      • Create a new detail view controller
      • Set its managedObjectContext property
      • Create a new master view controller
      • Set its managedObjectContext property
      • Set the master view controller's employeeViewController property to your detail view controller
      • Create a new split view controller
      • Set the split view controller's viewControllers property to an array containing your master and detail view controllers
      • Get the split view controller on the screen somehow, either by pushing it onto the navigation stack or setting it as your root view controller in applicationDidFinishLaunching:.