我有一个 View Controller ,它有一个应该调用的委托(delegate)方法,但它没有?
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");
}
出于某种原因,应该通知的 Controller 没有。通知 Controller 确实关闭了,这意味着提醒委托(delegate)的方法正在运行,但委托(delegate)不会运行该函数,因为它没有 NSLog。有什么想法吗?
最佳答案
您不能只指定一个对象符合协议(protocol)。您还必须将该对象指定为委托(delegate)。当您分配/初始化 NotifyingViewController 的实例时,将其委托(delegate)设置为 self,您应该没问题。
NotifyingViewController *notifyingInstance = [[NotifyingViewController alloc] init];
[notifyingInstance setDelegate:self];
执行此操作并指定该类符合协议(protocol)很重要,您已经在这一行中执行了该操作。
@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>
此外,在调用委托(delegate)方法时,最好将函数调用包装在 respondsToSelector:
检查中。
if ([self.delegate respondsToSelector:@selector(iWasAccepted)]) {
[self.delegate iWasAccepted];
}
关于ios - 未调用委托(delegate)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20134334/