0

I'm building an app that displays objects of a certain type in different view controllers (three or four UITableViewController in this case). In one place they're going to be something like latest objects, in some other place search results and so on... So at the end of the day, the controllers are almost entirely similar. They only have a few variations. For example, the SearchTableViewController has a search bar and implements methods that are necessary for the feature. Other than that, classes "share" most of their code. What can I do to make this code truly shared and not just duplicated as it is at the moment?

sf89
  • 5,088
  • 7
  • 24
  • 27
  • 1
    One technique often used to clean up table views which share similar data sources is to break the data source out into a separate object. There's a [good article about this on objc.io](http://www.objc.io/issue-1/lighter-view-controllers.html). You could create a base data source which implements most of the methods required, and then subclass it for more specific use cases, like the `SearchTableViewController`. – Sam Apr 18 '15 at 23:36
  • 1
    Something I was thinking about indeed. Thanks for that and the link. – sf89 Apr 18 '15 at 23:59

1 Answers1

1

If the UI is significantly different between the view controllers then you probably need to subclass. But if the differences are in the data model or the way the data is processed, then you can maybe use a generic view controller and design your data model to be more generic, so it can be viewed, sorted, or searched in unified manner.

In my experience, however, there's a natural instinct in all developers to avoid duplication at any cost, and it often gets in the way of getting the job done. From a pragmatic point-of-view, I'd suggest implementing it in the most "obvious" way, and think about optimising it later. Only then will you know where there are duplications you can get rid of.

Echelon
  • 7,306
  • 1
  • 36
  • 34
  • I really like your approach. I have already implemented these classes and have the duplication in place. Now is a good time to follow your suggestions. – sf89 Apr 18 '15 at 23:58