委托方法没被调用?

Jos*_*osa 9 cocoa-touch delegates objective-c uiviewcontroller ios

我有一个视图控制器与一个应该被调用的委托方法,但它没有?

NotifyingViewController.h

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

@interface NotifyingViewController : UIViewController

@property (nonatomic, weak) id<NotifyingViewControllerDelegate> delegate;
Run Code Online (Sandbox Code Playgroud)

NotifyingViewController.m

-(void)someMethod{
        [self.delegate iWasAccepted];
        [self dismissViewControllerAnimated:YES completion:nil];
}
Run Code Online (Sandbox Code Playgroud)

NotifiedViewController.h

#import "NotifyingViewController.h"  
@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>
Run Code Online (Sandbox Code Playgroud)

NotifiedViewController.m

-(void)iWasAccepted{
    [self saveIntoDB];
    NSLog(@"DELEGATE RAN");
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,应该通知的控制器不是.通知控制器确实忽略了警告委托IS运行的方法,但委托不运行该函数,因为它不是NSLog.有什么想法吗?

Mic*_*lum 24

您不能只指定对象符合协议.您还必须将该对象指定为委托.当你分配/初始化NotifyingViewController的实例时,将它的委托设置为self,你应该没问题.

NotifyingViewController *notifyingInstance = [[NotifyingViewController alloc] init];
[notifyingInstance setDelegate:self];
Run Code Online (Sandbox Code Playgroud)

这两者都很重要,并指定该类符合您已使用此行进行的协议.

@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>
Run Code Online (Sandbox Code Playgroud)

此外,在调用委托方法时,最好将函数调用包装在respondsToSelector:检查中.

if ([self.delegate respondsToSelector:@selector(iWasAccepted)]) {
    [self.delegate iWasAccepted];
}
Run Code Online (Sandbox Code Playgroud)