Marty
Marty

Reputation: 6174

How to send message to a parentViewController that is a subclass of UIViewController?

I have a UIViewController (MyViewController) and another view controller i'm presenting modally though MyViewController (call it SecondViewController). I want to be able to send a message to MyViewController from SecondViewController by using

[self.parentViewController hideSecondViewController];

But since parentViewController is defined as a UIViewController, and hideSecondViewController isn't a method of UIViewController, I get a warning saying "UIViewController may not respond to 'hideSecondViewController'". It works fine, because it CAN send the message successfully during the program, but since I #import SecondViewController in MyViewController, I can't #import MyViewController in SecondViewController. Any way around this?

Upvotes: 2

Views: 5661

Answers (2)

albertamg
albertamg

Reputation: 28572

When it comes time to dismiss a modal view controller, the preferred approach is to let the parent view controller do the dismissing. In other words, the same view controller that presented the modal view controller should also take responsibility for dismissing it whenever possible. Although there are several techniques for notifying a parent view controller that it should dismiss its modally presented child, the preferred technique is delegation.

In a delegate-based model, the view controller being presented modally must define a protocol for its delegate to implement. The protocol defines methods that are called by the modal view controller in response to specific actions, such as taps in a Done button. The delegate is then responsible for implementing these methods and providing an appropriate response. In the case of a parent view controller acting as a delegate for its modal child, the response would include dismissing the child view controller when appropriate.

Read more at the View Controller Programming Guide for iOS.


P.S:

since I #import SecondViewController in MyViewController, I can't #import MyViewController in SecondViewController.

To solve a circular dependency problem you can use a forward declaration.

Upvotes: 3

Zaky German
Zaky German

Reputation: 14334

It would be better to redesign your architecture as albertamg proposed but this should work:

[self dismissModalViewControllerAnimated:YES];

you can call dismiss on both the presenting and presented view controller and it will do the same thing.

Upvotes: 3

Related Questions