VC 被解散时如何调用委托?

How to call delegate when VC is dismissed?

我有两个VC。当第二个 VC 被关闭时,我需要调用委托函数。

在我的第一个 VC 或主要 VC 中,我在 .h 文件中给出了以下代码。

@interface FirstVC : ....<SecondVCDelegate>
-(void)didDismissViewController:(UIViewController*)vc;

但由于某种原因,未检测到第二个VC代表。

在展示第 2 个 VC 时,我给出了第 1 个 VC 的 .m 文件。

SecondVC *optionsVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVC"];
optionsVC.delegate = self;
optionsVC.view.backgroundColor = [UIColor blackColor];
optionsVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
[self presentViewController:optionsVC animated:YES completion:^{}];

在第二个 VC.h 文件中

@protocol SecondVCDelegate <NSObject>
 - (void)didDismissViewController:(UIViewController*)vc;
@end

@interface SecondVC : ...
 @property (nonatomic) id<SecondVCDelegate> delegate;
@end

在第二个 VC .m 文件中,我使用以下代码取消了

 [self dismissViewControllerAnimated:YES completion:nil];

你能指出我做错了什么并给出可能的解释吗?提前致谢。

这是 xcode 9 上的工作代码:

ViewController.m :

#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController () <SecondVCDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)action:(id)sender {
    SecondViewController *optionsVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    optionsVC.delegate = self;
    optionsVC.view.backgroundColor = [UIColor blackColor];
    optionsVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:optionsVC animated:YES completion:nil];
}

-(void) didDismissViewController:(UIViewController *)vc{
    NSLog(@"working controller : %@", vc);
}
@end

SecondViewController.h :

#import <UIKit/UIKit.h>

@protocol SecondVCDelegate <NSObject>
- (void)didDismissViewController:(UIViewController*)vc;
@end

@interface SecondViewController : UIViewController
 @property (weak, nonatomic) id<SecondVCDelegate> delegate;
@end

第二ViewController.m :

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)didmissAction:(id)sender {
    [self dismissViewControllerAnimated:true completion:^{
        [_delegate didDismissViewController:self];
    }];
}

@end

第 2 天 VC.m 这样做

首先在实现下面综合委托

@synthesize delegate;

之后在 viewController 解雇时使用它:

[self dismissViewControllerAnimated:YES completion:^{

    [self.delegate didDismissViewController: self];
}];