Protocols and Delegates in iOS
I have been thinking about MVC design pattern, and I was very confused.
I have ran into a problem while developing a social media app as a side project. I have custom UITableViewCell, and it sits in a UIViewController, from now on I will call it “controller class”. Problem was all the outlets of the cell are connected to the UITableViewCell’s particular class, from now on I will call it “view class”, in order to preserve MVC. And I want to perform segue while an image in a cell is tapped.
First, I have tried to do it in the “view class”. Although it violates MVC principals, I found it the easiest way to do. Usually, things may not go as planned :) After some thinking, googling and trying, I realized that it looked impossible and unnecessary to do. Then I started over everything.
I have attended many iOS Meetups in New York since October 2015, and I am in a Slack group of one of the best Meetup around. I asked my question there, and they answered me very fast. According to a friend, solution is the delegation. I have heard about protocols and delegations before, however I couldn’t think the solution was there. I was a huge enlightenment to me. I googled “reywenderlich protocols delegates”, and there was the solution :) http://www.raywenderlich.com/115300/swift-2-tutorial-part-3-tuples-protocols-delegates-and-table-views I wrote a protocol in my view class, and create a delegate variable, then I made my controller class conform the protocol. That was all, and it was very satisfying to solve the problem which made me uncomfortable for a time.
Thanks for the friend, reywenderlich, stackoverflow and surely google!
Happy coding!









