views:

220

answers:

2

I'm sure there is a correct way to do this, I'm new to objective-c and cocoa touch so I don't know what it is.

I have an application that has a (simplified) view hierarchy of

Window
  --Button
  --Button
  --Subview
    --Sub-Subview

What I'm trying to do is get the subview to do something in response to a touch event on one of the buttons. I can come up with a few methods of doing this, but I'm not sure which one is the preferred method.

  • Add an outlet to the Main view controller (handling the window) and storing a reference to the subview. When I need to message subview, I can simply pass the message I want (since I'll already have a reference). This seems workable, if a little ... fragile?

  • Add a second action to the button (the first is a method on the view controller, the second would be a method on the subview class). This seems problematic since it is important that the button's action in the view controller fire before the subview tries to handle the message

  • Some sort of delegate system?

  • Write a new view controller for the subview and have the main view controller pass that a message (not sure the correct way for the first controller to get a reference to the second. In addition, the code actually required for the subview is relatively small - a whole new controller seems like overkill).

  • Something else that I'm overlooking completely?

Some direction would be appreciate!

A: 

For a MVC purist perspective, all the logic should be in the controller. If you have only one controller, then the logic should go there, while the view classes are only responsible for layout and display.

Or you can have another controller, probably the best choice if your UI is rather complex.

Marco Mustapic
+1  A: 

You say that the button has an action on the view controller (which view controller?). And you want the action/method call on the subview to happen after that action. So I would suggest your view controller action post a notification of the event, and the subview can listen for that event. Alternatively, the view controller can have a connection to the subview.

That ensures the order of actions - most observation techniques will not ensure that order.

Matt Gallagher wrote a useful article, Five approaches to listening, observing and notifying in Cocoa on observing tehcniques which might help you.

Peter N Lewis