Reputation: 2724
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?
Upvotes: 2
Views: 1229
Reputation: 197
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.
Upvotes: 0
Reputation: 5488
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
Upvotes: 0
Reputation: 1734
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
Upvotes: 0
Reputation: 7935
I think parentVC
releases because of weak
reference. Try to use this method.
-(void)addThis{
NSLog(@"%@", self.parentVC);
[self.parentVC callParentMethod];
}
Upvotes: 2
Reputation: 13549
YourParentVC *parent = (YourParentVC*)[self presentingViewController];
parent.whatever = blah;
Upvotes: 0