ios - 未调用委托(delegate)方法?

标签 ios objective-c cocoa-touch uiviewcontroller delegates

我有一个 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/

相关文章:

ios - XCode 找不到#import "ASIHTTPRequest.h"IOS 4.3

objective-c - NSTextView 拖放 -- 拖放后字符不可见

objective-c - 检查电子邮件地址在 iOS 上是否有效

objective-c - 子类化 UIWindow - 需要预处理器帮助

iphone - writeImageToSavedPhotosAlbum 太慢?

ios - 如何在 iOS 7 中滚动到 UITableView 的顶部

ios - iOS UITableView reloadData显示空白屏幕

android - 视频无法在 Android (chrome) 和 iOS (safari) 上播放

iOS 缓存 UIWebView

ios - 如何使用CorePlot框架和swift 3制作折线图?