views:

308

answers:

4

I have a ViewController class called GamePlay. In GamePlay there is a nested class called MyPinAnnotationView. When MyPinAnnotation's method TouchesBegan() gets called, I want to call a method CheckAnswer() from the parent GamePlay.

I do not want to create a new GamePlay instance because I have variables and instances already set. Can I access the parent in some way? ( Other than event listeners)

+1  A: 

If the methods you want to access are not static, then you will need a reference to the parent object (I commonly pass the parent object reference in as a constructor parameter) in order to access its methods. After all, your child class needs to know which instance of the parent class it is related to.

David
Thanks. Makes sense.
Bryan
+1  A: 

The easy/quick way would be to keep a reference to the parent class in the child object, make CheckAnswer() public, then it's easy to call the method whenever needed... but you may want to go back and review the design to make sure this is appropriate.

Jon Seigel
A: 

Nested classes should only be utilized by the parent class (see this post). They shouldn't be publicly visible to other classes unless there is a really good reason. Which there isn't.

I would suggest refactoring this. Try moving all the API for GamePlay into the GamePlay class. In other words, TouchesBegan() should be called on the GamePlay class, which then calls into the MyPinAnnotations class.

No one else should know about MyPinAnnotations class - if they need to, then it is indicative of a design failure.

womp
+6  A: 

The nested class will only be able to reference static members in the parent. If you want to access instance members, you need to get a reference to the instance. The simplest way to do this is to add it as a parameter to the constructor of MyPinAnnotationView like so:

class MyPinAnnotationView
{
  private GamePlay gamePlay;

  public MyPinAnnotationView(GamePlay gamePlay)
  {
    this.gamePlay = gamePlay;
  }

  public void TouchesBegan()
  {
    this.gamePlay.CheckAnswer();
  }
}

When you instantiate MyPinAnnotationView from GamePlay, just do this:

MyPinAnnotation annotation = new MyPinAnnotation(this);
asbjornu