Reputation: 5191
I am quite new to IOS, and I was working with delegates to call a method in parent ViewController.
ViewControllerRegistration.h
@protocol RegistrationViewControllerDelegate;
@interface ViewControllerRegistration : UIViewController
@property (nonatomic, weak) id<RegistrationViewControllerDelegate> delegate;
- (IBAction)registerNewUser:(id)sender;
@end
// 3. Definition of the delegate's interface
@protocol RegistrationViewControllerDelegate <NSObject>
-(void)loginResult:(NSString*)loginData;
@end
ViewControllerRegistration.m
- (void)registerNewUser:(id)sender {
id<RegistrationViewControllerDelegate> strongDelegate = self.delegate;
// Our delegate method is optional, so we should
// check that the delegate implements it
if ([strongDelegate respondsToSelector:@selector(loginResult:)]) {
[strongDelegate loginResult: @"@WHY YOU NOT BEING CALLED?"];
}
Parents:
ViewController.h
#import "ViewControllerRegistration.h"
@interface ViewController : UIViewController <GPPSignInDelegate,FBSDKLoginButtonDelegate,RegistrationViewControllerDelegate>
@end
ViewController.m
@implementation ViewController
@synthesize signInButton;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ViewControllerRegistration *detailViewController = [[ViewControllerRegistration alloc] init];
// Assign self as the delegate for the child view controller
detailViewController.delegate = self;
}
//Local Strategy
- (IBAction)navigateToLocalSignUpNavBtn:(id)sender {
[self performSegueWithIdentifier:@"SegueRegisterUserAction" sender:self];
}
// Implement the delegate methods for RegistrationViewControllerDelegate
-(void)loginResult:(NSString*)loginData{
NSLog(@"I am called");
//^Above is never printed. That means delegate method is never called
}
Please note, my parent view controller is embedded in a navigation controller.
The delegate method is never called. Tried debugging, but in vain.
Upvotes: 0
Views: 71
Reputation: 9825
The view controller you are creating in viewDidLoad
isn't the same one that you will be segueing to. It's another instance that will be deallocated at the end of the method. You need to access the correct instance in prepareForSegue
and set the delegate there.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"SegueRegistrationUserAction"]) {
[(ViewControllerRegistration *)segue.destinationViewController setDelegate:self];
}
}
Upvotes: 1
Reputation: 38162
Yesterday, I had explained this in length on this thread. Please take a look and let me know if you have any specific question post that. I hope this would help you.
Upvotes: 1