Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate method not being called?

I have a view controller with a delegate method that should be called, but it doesn't?

NotifyingViewController.h

@protocol NotifyingViewControllerDelegate <NSObject>
@required
- (void)iWasAccepted;
@end

@interface NotifyingViewController : UIViewController

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

NotifyingViewController.m

-(void)someMethod{
        [self.delegate iWasAccepted];
        [self dismissViewControllerAnimated:YES completion:nil];
}

NotifiedViewController.h

#import "NotifyingViewController.h"  
@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>

NotifiedViewController.m

-(void)iWasAccepted{
    [self saveIntoDB];
    NSLog(@"DELEGATE RAN");
}

For some reason, the controller that should be notified isn't. The Notifying controller does dismiss meaning the method that alerts the delegate IS run, but the delegate doesn't run the function because it doesn't NSLog. Any ideas why?

like image 753
Josue Espinosa Avatar asked Nov 21 '13 23:11

Josue Espinosa


1 Answers

You can't just specify that an object conforms to a protocol. You must also assign that object as the delegate. When you alloc/init the instance of NotifyingViewController, set its delegate to self and you should be fine.

NotifyingViewController *notifyingInstance = [[NotifyingViewController alloc] init];
[notifyingInstance setDelegate:self];

It is important to both do this, and specify that the class conforms to the protocol, which you're already doing with this line.

@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>

Additionally, when calling delegate methods, it's good practice to wrap the function calls in respondsToSelector: checks.

if ([self.delegate respondsToSelector:@selector(iWasAccepted)]) {
    [self.delegate iWasAccepted];
}
like image 166
Mick MacCallum Avatar answered Oct 14 '22 11:10

Mick MacCallum