Will handling UIButton touch event inside a UITableViewCell subclass violate MVC?

239 views Asked by At

There is a UITableViewCell subclass with a UIButton inside. A web call should be made when the button is pressed.

The question is whether I should set the action in the controller, or can the action be set within the UITableViewCell subclass? Will the second option violate MVC pattern?

3

There are 3 answers

0
tailec On BEST ANSWER

The second option will certainly violate MVC pattern. ViewController works like a glue between your models, views and contains all the business logic. ViewController should receive action then make your api call and put formatted data to your views.

Usually in my project I always try to move networking code into separated set of classes which can handle fetching data from API, transforming from JSON/XML to model objects and formatting them (string date object to NSDate object etc.). Then I can call simple looking method in my ViewController and populate views/tableview cells.

On the other hand,

If you have some time you can look at MVVM which is getting more popular. There are some links (start with sprynthesis which is AWESOME):

  1. www.sprynthesis.com
  2. objc.io
  3. cocoasamurai
  4. raywenderlich

And some sample apps:

  1. C-41
  2. vinylogue
  3. GroceryList

That helped me to understand MVC more deeply thanks to comparision to MVVM.

Don't be scared with usage of ReactiveCocoa, you can always adopt MVVM without it but it's worth to look at. (It has really steep learning curve and I still feel like an idiot)

Also there is a great article about design patterns with iOS implementation:

raywenderlich design patterns

0
Albara On

Well you can delegate the action to the controller from the subclass, that way it'll be handled in the controller, clear, and doesn't violate MVC.

0
agy On

I don't recommend to set the action within the UITableViewCell. What would you do if you need to wait for the answer and the cell needs to be recycle? I will set the action in the controller. This controller should call another class in charge of performing the web call.