Arcadian
Arcadian

Reputation: 4350

How to call function/method in parent view controller

I have a MyViewController that has a UINavigationController as a subview and the UINavigatioController has a CustomView popped on the stack. What I want to do is in the CustomView is to call a method in MyViewController.. so I tried this:

UINavigationController *main = (UINavigationController*)[self parentViewController];    
MyViewController *parentContainer = (MyViewController*)[main parentViewController];
[parentContainer myParentMethod];

this code is not correct.

Upvotes: 2

Views: 2883

Answers (2)

Albert Renshaw
Albert Renshaw

Reputation: 17882

Define the following macro in your child .m

#define parentVC (\
(^UIViewController*(void){\
UIViewController *viewController = nil;\
for (UIView *next = [self isKindOfClass:[UIViewController class]]?[((UIViewController *)self).view superview]:[((UIView *)self) superview]; next; next = next.superview) {\
UIResponder *nextResponder = [next nextResponder];\
if ([nextResponder isKindOfClass:[UIViewController class]]) {\
viewController = (UIViewController *)nextResponder;\
break;\
}\
}\
return viewController;\
})()\
)

Then in your child-vc just cast said macro to parent class type and execute the method you want, like this:

[(MyParentController *)parentVC myParentMethod];

Upvotes: 0

MHC
MHC

Reputation: 6405

The parentViewController property only works for the navigation controller, the tab bar controller, or in a modal presentation relationship. Although a MyViewController object has the view of a UINavigationController object as a subview, it doesn't mean that MyViewController is the parentViewController of the UINavigationController object.

If you have to keep this design and need to access the MyViewController object from a CustomView object, the best way of doing it is to let the CustomView object have a weak reference to the MyViewController object (like delegate properties).

Upvotes: 1

Related Questions