2

Noob question fellas, but I cant get it.

I've got a View Controller that loads in a separate View Controller. I would like to be able on a button press to call a method inside the parent View controller. So here is what i've got

parent VC:

   .h
    -(void)callParentMethod;



    .m

    -(void)viewDidLoad{
    self.childVC.parentVC = self;
    }

-(void)callParentMethod{
NSLog(@"Hello?");
}

child VC:

.h

#import "TheParentViewController.h"

@property (nonatomic, weak) TheParentViewController *parentVC;


.m

-(void)addThis{
[self.parentVC callParentMethod];
}

I get no errors, the child VC method addThis seems to call the method, but the NSLog is never called. Any thoughts what i'm doing wrong?

James Dunay
  • 2,714
  • 8
  • 41
  • 66
  • http://stackoverflow.com/questions/8055052/call-a-parent-view-controller-through-a-navigationcontroller/8055480#8055480 – user523234 Sep 17 '13 at 03:45

5 Answers5

2

I think parentVC releases because of weak reference. Try to use this method.

-(void)addThis{
NSLog(@"%@", self.parentVC);
[self.parentVC callParentMethod];
}
Sviatoslav Yakymiv
  • 7,887
  • 2
  • 23
  • 43
0
YourParentVC *parent = (YourParentVC*)[self presentingViewController];

parent.whatever = blah;
Tommy Devoy
  • 13,441
  • 3
  • 48
  • 75
0

I am not quite sure what your application is, but you should not have to keep a reference to the parent view controller. A UIViewController already has a property called parentViewController which you can use in the following way:

[self.parentViewController methodToCall];

This will call a method on the parent view controller. You may need to cast the object in order to call custom methods

[(TheParentController *)self.parentViewController methodToCall];

This of course assumes that the child view controller's view is a subview of the parent view controller view. Hope this helps

tomasbasham
  • 1,695
  • 2
  • 18
  • 37
0

Check whether your parent view controller is allocated.

   parentnvc = [ParentViewController alloc]initWithNibName:@"somenib" bundle:nil];

if parentvc is allocated and initialised and call the method

slysid
  • 5,236
  • 7
  • 36
  • 59
0

You can create a property in child view controller say,

@class ParentVC;
@property(weak,nonatomic)ParentVC *parentVCreference;

and get the reference for the Parent view controller as follows

self.parentVCreference=(ParentVC*)self.parentViewController;

then you can call any exposed methods from ParentVC as follows

[self.parentVCreference parentVCMethod];

Note: You need to import header of ParentVC in ChildVC implementation file.

Nikhil Augustine
  • 187
  • 2
  • 12