37

I have a problem when implementing the MVC-pattern on iOS. I have searched the Internet but seems not to find any nice solution to this problem.

Many UITableViewController implementations seems to be rather big. Most examples I have seen lets the UITableViewController implement <UITableViewDelegate> and <UITableViewDataSource>. These implementations are a big reason why UITableViewControlleris getting big. One solution would be to create separate classes that implements <UITableViewDelegate> and <UITableViewDataSource>. Of course these classes would have to have a reference to the UITableViewController. Are there any drawbacks using this solution? In general I think you should delegate the functionality to other "Helper" classes or similar, using the delegate pattern. Are there any well established ways of solving this problem?

I do not want the model to contain too much functionality, nor the view. I believe that the logic should really be in the controller class, since this is one of the cornerstones of the MVC-pattern. But the big question is:

How should you divide the controller of a MVC-implementation into smaller manageable pieces? (Applies to MVC in iOS in this case)

There might be a general pattern for solving this, although I am specifically looking for a solution for iOS. Please give an example of a good pattern for solving this issue. Please provide an argument why your solution is awesome.

2
  • 1
    "Also an argument why this solution is awesome." :)
    – occulus
    Commented Nov 30, 2012 at 14:07
  • 1
    That's a little bit beside the point, but the UITableViewController mechanics seem quite strange to me, so I can relate to the problem. I'm actually glad I use MonoTouch, because MonoTouch.Dialog specifically makes it that much easier to work with tables on iOS. In the meantime, I'm curious what other, more knowledgeable people might suggest here... Commented Dec 3, 2012 at 14:05

6 Answers 6

43

I avoid using UITableViewController, as it puts lots of responsibilities into a single object. Therefore I separate the UIViewController subclass from the data source and delegate. The view controller's responsibility is to prepare the table view, create a data source with data, and hook those things together. Changing the way the tableview is represented can be done without changing the view controller, and indeed the same view controller can be used for multiple data sources that all follow this pattern. Similarly, changing the app workflow means changes to the view controller without worrying about what happens to the table.

I've tried separating the UITableViewDataSource and UITableViewDelegate protocols into different objects, but that usually ends up being a false split as almost every method on the delegate needs to dig into the datasource (e.g. on selection, the delegate needs to know what object is represented by the selected row). So I end up with a single object that's both the datasource and delegate. This object always provides a method -(id)tableView: (UITableView *)tableView representedObjectAtIndexPath: (NSIndexPath *)indexPath which both the data source and delegate aspects need to know what they're working on.

That's my "level 0" separation of concerns. Level 1 gets engaged if I have to represent objects of different kinds in the same table view. As an example, imagine that you had to write the Contacts app—for a single contact, you might have rows representing phone numbers, other rows representing addresses, others representing email addresses, and so on. I want to avoid this approach:

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  if ([object isKindOfClass: [PhoneNumber class]]) {
    //configure phone number cell
  }
  else if …
}

Two solutions have presented themselves so far. One is to dynamically construct a selector:

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  NSString *cellSelectorName = [NSString stringWithFormat: @"tableView:cellFor%@AtIndexPath:", [object class]];
  SEL cellSelector = NSSelectorFromString(cellSelectorName);
  return [self performSelector: cellSelector withObject: tableView withObject: object];
}

- (UITableViewCell *)tableView: (UITableView *)tableView cellForPhoneNumberAtIndexPath: (NSIndexPath *)indexPath {
  // configure phone number cell
}

In this approach, you don't need to edit the epic if() tree to support a new type - just add the method that supports the new class. This is a great approach if this table view is the only one that needs to represent these objects, or needs to present them in a special way. If the same objects will be represented in different tables with different data sources, this approach breaks down as the cell creation methods need sharing across the data sources—you could define a common superclass that provides these methods, or you could do this:

@interface PhoneNumber (TableViewRepresentation)

- (UITableViewCell *)tableView: (UITableView *)tableView representationAsCellForRowAtIndexPath: (NSIndexPath *)indexPath;

@end

@interface Address (TableViewRepresentation)

//more of the same…

@end

Then in your data source class:

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  return [object tableView: tableView representationAsCellForRowAtIndexPath: indexPath];
}

This means that any data source that needs to display phone numbers, addresses etc. can just ask whatever object is represented for a table view cell. The data source itself no longer needs to know anything about the object being displayed.

"But wait," I hear a hypothetical interlocutor interject, "doesn't that break MVC? Aren't you putting view details into a model class?"

No, it doesn't break MVC. You can think of the categories in this case as being an implementation of Decorator; so PhoneNumber is a model class but PhoneNumber(TableViewRepresentation) is a view category. The data source (a controller object) mediates between the model and the view, so the MVC architecture still holds.

You can see this use of categories as decoration in Apple's frameworks, too. NSAttributedString is a model class, holding some text and attributes. AppKit provides NSAttributedString(AppKitAdditions) and UIKit provides NSAttributedString(NSStringDrawing), decorator categories that add drawing behaviour to these model classes.

5
  • What is a good name for the class that is working as data source and table view delegate? Commented Apr 18, 2013 at 11:42
  • 1
    @JohanKarlsson I often just call it the data source. It's a bit sloppy perhaps, but I combine the two often enough to know that my "data source" is an adaptation onto Apple's more restricted definition.
    – user4051
    Commented May 19, 2013 at 12:09
  • 1
    This article: objc.io/issue-1/table-views.html proposes a way to handle multiple cell types whereby you work out the cell class in the cellForPhotoAtIndexPath method of the data source, then call an appropriate factory method. Which of course is only possible if particular classes predictably occupy particular rows. Your system of view-generating categories-on-models is much more elegant in practice, I think, although it is maybe an unorthodox approach to MVC! :)
    – Benji XVI
    Commented Jan 3, 2014 at 16:32
  • 1
    I have try to demo this pattern at github.com/yonglam/TableViewPattern. Hope it's useful for someone.
    – Andrew
    Commented Jun 16, 2014 at 2:22
  • 1
    I'll vote a definitive no for the dynamic selector approach. It is very dangerous as the issues only manifest at run time. There's no automated way to make sure that the given selector exists and that it typed correctly and this kind of approach will fall apart eventually and is a nightmare to maintain. The other approach, however, is very clever.
    – mkko
    Commented Oct 1, 2014 at 20:09
3

People do tend to pack a lot into the UIViewController/UITableViewController.

Delegation to another class (not the view controller) usually works out fine. The delegates don't necessarily need a reference back to the view controller, since all delegate methods get passed a reference to the UITableView, but they will need access somehow to the data they're delegating for.

A few ideas for reorganisation to reduce length:

  • if you're constructing the table view cells in the code, consider loading them instead from a nib file or from a storyboard. Storyboards allow prototype and static table cells -- check out those features if you're not familiar

  • if your delegate methods contain a lot of 'if' statements (or switch statements) that's a classic sign that you can do some refactoring

It always felt a bit funny to me that the UITableViewDataSource was responsible for getting a handle on the correct bit of data and configuring a view to show it. One nice refactoring point might be to change your cellForRowAtIndexPath to get a handle on the data that needs displaying in a cell, then delegate the creation of the cell view to another delegate (e.g. make a CellViewDelegate or similar) which gets passed in the appropriate data item.

4
  • This is a nice answer. However a couple of questions arises in my head. Why do you find a lot of if-statements (or switch-statements) to be bad design? Do you actually mean, a lot of nested if- and switch-statements? How do you re-factor to avoid if- or switch-statements? Commented Dec 2, 2012 at 19:22
  • @JohanKarlsson one technique is via polymorphism. If you need to do one thing with one type of object and something else with a different type, make those objects different classes and let them choose the work for you.
    – user4051
    Commented Dec 3, 2012 at 14:44
  • @GrahamLee Yes, I know polymorphism ;-) However I am not sure how to apply it in this context. Please elaborate on this. Commented Dec 3, 2012 at 19:26
  • @JohanKarlsson done ;)
    – user4051
    Commented Dec 4, 2012 at 8:50
2

Here is roughly what I'm currently doing when facing similar problem:

  • Move data related operations to XXXDataSource class(which inherits from BaseDataSource : NSObject). BaseDataSource provides some convenient methods like - (NSUInteger)rowsInSection:(NSUInteger)sectionNum; , subclass overrides data loading method(as apps usually have some sort of offlie cache load method looks like - (void)loadDataWithUpdateBlock:(LoadProgressBlock)dataLoadBlock completion:(LoadCompletionBlock)completionBlock; so that we can update UI with cached data received in LoadProgressBlock while we are updating info from network, and in completion block we refresh UI with new data and remove progess indicators, if any). Those classes do NOT conform to UITableViewDataSource protocol.

  • In BaseTableViewController(which conforms to UITableViewDataSource and UITableViewDelegate protocols) I have reference to BaseDataSource, which I create during controller init. In UITableViewDataSource part of controller I simply return values from dataSource(like - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [self.tableViewDataSource sectionsCount]; }).

Here is my cellForRow in base class(no need to override in subclasses):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [NSString stringWithFormat:@"%@%@", NSStringFromClass([self class]), @"TableViewCell"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [self createCellForIndexPath:indexPath withCellIdentifier:cellIdentifier];
    }
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

configureCell must be overriden by subclasses and createCell returns UITableViewCell, so if you want custom cell, override it too.

  • After base things are configured(actually, in first project which uses such scheme, after that this part can be reused) what is left for BaseTableViewController subclasses is:

    • Override configureCell(this usually transforms to asking dataSource for object for index path and feeding it to cell's configureWithXXX: method or getting object's UITableViewCell representation like in user4051's answer)

    • Override didSelectRowAtIndexPath:(obviously)

    • Write BaseDataSource subclass which takes care of working with necessary part of Model(suppose there are 2 classes Account and Language, so subclasses will be AccountDataSource and LanguageDataSource).

And that's all for table view part. I can post some code to GitHub if needed.

Edit: some recomendations can be found at http://www.objc.io/issue-1/lighter-view-controllers.html (which has link to this question) and companion article about tableviewcontrollers.

2

My view on this is that the model needs to give an array of object that are called ViewModel or viewData encapsulated in a cellConfigurator. the CellConfigurator holds the CellInfo needed to deque it and to configure the cell. it gives the cell some data so the cell can configure its self. this works too with section if you add some SectionConfigurator object that hold the CellConfigurators. I started using this a while back initially just giving the cell a viewData and had the ViewController deal with dequeuing the cell. but I read an article that pointed to this gitHub repo.

https://github.com/fastred/ConfigurableTableViewController

this may change the way you are approaching this.

2

I have recently wrote an article about how to implement delegates and data sources for UITableView: http://gosuwachu.gitlab.io/2014/01/12/uitableview-controller/

The main idea is to split responsibilities into separate classes, like cell factory, section factory, and provide some generic interface for the model that UITableView is going to display. Diagram below explains it all:

enter image description here

1
  • This link is no longer working.
    – koen
    Commented Dec 18, 2016 at 13:44
1

Following SOLID principles will solve any kind of problems like these.

If you want to your classes to have JUST A SINGLE responsibility, you should define separate DataSource and Delegate classes and simply inject them to the tableView owner (could be UITableViewController or UIViewController or anything else). This is how you overcome separation of concern.

But if you just want to have clean and readable code and want to get rid of that massive viewController file and you are in Swif, you can use extensions for that. Extensions of the single class can be written in different files and all of them have access to each other. But this is nit truly solves SoC issue as I mentioned.

1
  • The extension was good enough! Actually rewiring it to more interfaces accomplishes nothing (yes, I know about testing, etc - and I don't care at all about that for my purposes atm).
    – Radu
    Commented Feb 5, 2020 at 9:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.