Ben Thompson
Ben Thompson

Reputation: 4833

Using UIViewController for protocol

I have built a UITableViewController for my app which interacts with my core data model. It's primary purpose is to be pushed onto the navigation controller and display a list of entities and allow me to edit / select and drill down into info them etc...

However, elsewhere in my app, I now want to modally display a simple picker to select one of these entities. I think the best way to implement this is building a protocol to handle the picker that can send messages back to my delegate about whether the user cancelled or selected an entity etc...

As so much of the coding will be the same, my question is this: is it possible/or in any way advisable to enable the UITableViewController as a protocol?

i.e. when displayed normally, it behaves as it does currently (a standard subclass of UIViewController) but then is also able to be presented modally by a delegate and pass messages to a delegate?

Keen to her thoughts on best practice?

Upvotes: 1

Views: 1079

Answers (1)

soryu2
soryu2

Reputation: 144

You don’t even need a formal protocol. Just give your UITableViewController a @property (nonatomic, assign) id delegate when instantiating it from the other controller. Set that as the delegate. Use id to not couple your classes too tightly and do not retain the delegate.

Implement two methods for didCancelPicking...:(id)sender and didPick...:(id)sender item:(id)pickedItem in the calling controller.

Now when viewing the UITableViewController modally you need to do two things. Supply a cancel button + react to that (didCancelPicking...) and probably modify tableView:didSelectRowAtIndexPath: to send didPick... to the delegate. Always test the delegate with respondsToSelector: and in case it does performSelector:withObject:. Always put the sender as the first argument in these delegate methods.

Also, always show and hide the modal controller from the calling class. Do not let it remove itself from a UINavigationController for instance.

These are the best practices I can think off the top of my hat.

Regarding your specific code reuse here: You have to decide if your code gets too messy, when you reuse that UITableViewController and want to change how it behaves when shown modally. E.g. you might later want to prevent editing and drilling down in that case. You could of course always encapsulate this in if (self.delegate) checks, but...

Upvotes: 1

Related Questions