Reputation: 7360
Just when I thought I had my head around how delegates work, it seems I am missing something.
I've setup a delegate like so:
ViewControllerA.h
@protocol LoginDelegate <NSObject>
-(void)userLoginSuccessful;
@end
@interface BBLoginViewController : BBBaseViewController
@property (weak, nonatomic) id <LoginDelegate> delegate;
@end
ViewControllerA.m
-(void)someMethod
{
if ([self.delegate respondsToSelector:@selector(userLoginSuccessful)]){
[self.delegate userLoginSuccessful];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
ViewControllerB.m
#import "ViewControllerA.h"
@interface ViewControllerB () <UITableViewDataSource, UITableViewDelegate, LoginDelegate>
-(void)viewWillAppear:(BOOL)animated
{
ViewControllerA *loginViewController = [[ViewControllerA alloc]init];
loginViewController.delegate = self;
}
#pragma mark - Login Delegate
-(void) userLoginSuccessful
{
NSLog (@"Delegate fired!");
}
After all this my delegate method does not fire. What am I doing wrong? I looked at this SO answer and when checking the delegate is not nil - it is not. Its set to ViewControllerB
.
Upvotes: 0
Views: 864
Reputation: 42977
Set the delgate
before presenting ViewControllerB
. The below code is not required anymore
-(void)viewWillAppear:(BOOL)animated
{
ViewControllerA *loginViewController = [[ViewControllerA alloc]init];
loginViewController.delegate = self;
}
Dont do like that. It will give you unexpected results. Remember always set the delegate before moving to the next view. If you are presenting modally just before presentViewController
of if you are using segue in prepareForSegue
Upvotes: 2
Reputation: 122391
This code:
-(void)viewWillAppear:(BOOL)animated
{
ViewControllerA *loginViewController = [[ViewControllerA alloc]init];
loginViewController.delegate = self;
}
Will create a ViewControllerA
object and then (almost) immediately destroy it and is not what you intended.
You probably want to be setting the delegate in the prepareForSegue:
method anyway...
Upvotes: 3