Delegate method not being called?

2020-05-27 15:50发布

问题:

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?

回答1:

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];
}