soleil
soleil

Reputation: 13085

Why is my delegate becoming nil?

I've done this delegation pattern a million times. On the million and one-th time I'm getting a nil delegate:

CatViewController *vc = [[UIStoryboard storyboardWithName:@"Cat" bundle:nil] instantiateInitialViewController];
vc.delegate = self;
[self presentViewController:vc animated:YES completion:^{
        DDLogWarn(@"[%@ %@] delegate: %@", THIS_FILE, THIS_METHOD, vc.delegate); //here the delegate is valid
    }];

@protocol CatViewControllerDelegate;

@interface CatViewController : UIViewController

@property (weak, nonatomic) id <CatViewControllerDelegate> delegate;

@end

@protocol CatViewControllerDelegate <NSObject>

@required
- (void)catViewController:(CatViewController*)catVC didFinishWithSuccess:(BOOL)success;

@end

However, in viewDidLoad of CatViewController, self.delegate is already nil, and of course is nil when I try to do this:

    [self.delegate catViewController:self didFinishWithSuccess:YES];

Why is the catViewController's delegate becoming nil?

Upvotes: 2

Views: 1697

Answers (3)

soleil
soleil

Reputation: 13085

The problem was that the CatViewController was embedded in a Navigation Controller in the Storyboard. Therefore instantiateInitialViewController was not returning a CatViewController, although everything appeared fine on screen. The fix:

UINavigationController *navVC = [[UIStoryboard storyboardWithName:@"Cat" bundle:nil] instantiateInitialViewController];
CatViewController *catVC = navVC.viewControllers[0];
catVC.delegate = self;

Upvotes: 3

DennyLou
DennyLou

Reputation: 313

Did you try to declare the delegate like this instead?

@property (unsafe_unretained, nonatomic) id <CatViewControllerDelegate> delegate;

Upvotes: -2

Daniel T.
Daniel T.

Reputation: 33967

You have:

vc.delegate = self;

Whatever self is, it is being deleted by the time your new view controller's viewDidLoad gets called. To test this theory, put a dealloc method in that class and put a breakpoint in it.

Upvotes: 2

Related Questions