0

i m adding a custom view to a view controller , by the following code

[bTVC addSubview:customView];

now i want to call a instance method of parent viewController in the custom view's class like this

[self.parentViewController instanceMethod];

is that possible ? how can i do that ?

Subbu
  • 2,063
  • 4
  • 29
  • 42
  • create an object of the parent view and use it to call its methods – IronManGill Jan 29 '13 at 09:13
  • but that would mean creating a new object .. cant i use the existing object of ViewController on which the custom view has been added ?? – Subbu Jan 29 '13 at 09:19

2 Answers2

4

the "normal" method should be to implement a property (not retained) delegate pointing to your parent viewController, but you may prefer to use something like this:

-(MyCustomUIViewController*)findParentUIViewControllerInSuperViews:(UIView*)myView {
    for (UIView* next = [myView superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[MyCustomUIViewController class]]) {
            return (MyCustomUIViewController*)nextResponder;
        }
    }
    return nil;
}

now just call:

MyCustomUIViewController* myParentViewController = (MyCustomUIViewController*)[self findParentUIViewControllerInSuperViews:self];
[myParentViewController instanceMethod];

anyway, i also recommend you to learn how delegate works, it's useful in many cases and you'll surely need it sooner or later...

meronix
  • 6,175
  • 1
  • 23
  • 36
0

There is no addSubview method in NSViewController. You can find it in NSView. if bTVC is an instance of NSView (or a subclass of) you can get what you call parent view by sending superview to self : [self superview] or self.superview. It'll return bTVC in your example. NSViewController works differently you can read full documentation here

Pyroh
  • 216
  • 2
  • 13