Search code examples
iosswiftuitableviewcore-datansfetchedresultscontroller

6 separate UIViewControllers or just one with different data sources decided at segue?


I'm building an iOS app in Swift which has a start page with 6 buttons. Each of those buttons will segue to a table view controller whose data is managed with an NSFetchedResultsController (application uses core data). Now, I can see it being easy to create 6 UITableViewControllers however I'm wondering if it would be more sensible to send each button to the same UITableViewController and just change the data loaded/managed by setting some kind of flag in the prepareForSegue method?

What's the best practice here? It seems crazy to have 6 tableViewControllers each backed by it's own NSFetchedResultsController when big portions of the required code for each are reusable and could be subclassed out and used multiple times.


Solution

  • If you can code a single view controller in a way that supports all six with a single code base, reusing a single UITableViewController makes perfect sense. Other approaches include

    • Composition - make a class for the data source, configure it before opening the table view, and pass it to the table view on segue
    • Subclassing - make an abstract base view controller, and extend it six times. Override an abstract method or two to reduce the amount of repetition
    • Helper - make a class that holds all reusable logic shared across the six view controllers, and call its methods from six very slip controllers.

    One thing you want to avoid is code like this:

    if (viewControllerType == ViewControllerOne) {
         doSomethingSpecial()
    } else if (viewControllerType == ViewControllerTwo) {
         doSomethingElseSpecial()
    } ... // and so on
    

    When you have a chain like this, you know that you've missed an opportunity to subcllass.