Property scope question

Discussion in 'iOS Programming' started by aukemid, Oct 28, 2010.

  1. aukemid macrumors newbie

    Joined:
    Mar 26, 2010
    #1
    I'm new to iPhone programming, followed some tutorials, and I'm now building my first app.

    In my app I'm going to use multiple Views so I have 3 classes which extend UIViewController. To switch between these views I have a class called SwitchView which has properties of the 3 views and methods to show these. This SwitchView is a property of the appDelegate.

    In one of the Views I have a buttons which calls a method in de corresponding class. This method now needs to switch views, so it needs to call a method in SwitchView.

    This class doesn't has a instance of SwitchView and the methods are private. How can I call this method? Can I get the switchView instance from the appDelegate?
     
  2. Luke Redpath macrumors 6502a

    Joined:
    Nov 9, 2007
    Location:
    Colchester, UK
    #2
    You can get access to the delegate through the shared application object but it's not how I would do it.

    This is a very basic OOP problem. An object has a dependency on another object so it needs a way of accessing that object. I find it much better to make an objects dependencies explicit rather than them acquiring them through some kind of shared object. What are the different ways of injecting a dependency?

    Constructor injection is one way but this isn't useful if you don't have control over an objects initialisers or you don't call them explicitly (e.g. They have been loaded from a NIB).

    In this case, I would use a property to inject the dependency. Give your view controllers a switchView property and have your application delegate assign it's switchView object to each controller using this property. Each controller now has access to the switchView object it needs without having to know about the app delegate.

    Looking at this from a higher level, is there a reason why you aren't using one of the built-in mechanisms for managing and navigating a group of view controllers (e.g. Navigation and tab bar controllers, or modal view controller display)?
     

Share This Page