Delegate with instance variable of view controller

| | August 10, 2015

I am creating an Obj-C application, and am working on a single view. However, within this viewful, there is enough logic that I want to separate that from the view controller itself. I decided to create a delegate, but my current problem is how these two should communicate. Two potential solutions I have been considering:

1) An instance variable of the view controller within the delegate. Then when any view updates need to happen I simply call the appropriate method on that instance variable.

2) Notifications being fired off by the delegate and add the view controller as an observer.

Is there one method that is obviously superior or does it depend on the situation? I don’t know the proper way to go about this and am trying to approach this from the correct angle.

2 Responses to “Delegate with instance variable of view controller”

  1. This is a broad question. However, if what you are trying to do is simply refactor existing code to make maintenance easier without changing any functionality, use instance variables. Your code execution sequence will be unchanged and your method can return status information on the execution results. Your original controller and your new refactored class are tightly coupled – know a lot about each other.

    Notification logic is event-based (something interesting happens and an event is sent to registered observers). The logic is executed when the observer receives the event so there is no guarantee you can control the exact execution sequence, and the caller does not know if the observer received or successfully processed the message – the are loosely coupled.

    When in doubt look at what Apple does in its framework classes like UITableView. Delegates give you fine control over when things happen.

  2. If it’s non-UI related responsibilities you want to separate from the view controller, it’s very natural and recommended to have another object responsible for those tasks. In this case, you can either have a singleton for those responsibilities, or simply a NSObject subclass instance strongly referenced in your view controller.

    If it’s pure UI related tasks you want to separate from the view controller, just to organize the source code clearer, you should instead create categories for the view controller and name the categories according to their responsibilities, for example, MyViewController(Localization), MyViewController(UserInteration), etc.

Leave a Reply