iosobjective-cdelegatesdismissviewcontroller

dismisscontroller delegate method not working


I have 2 viewcontrollers, first VC contains backButton.

firstVC.h

@protocol DVDelegate <NSObject>
-(void)DVViewControllerDismissed:(NSString *)stringForFirst;
@end

and also contains delegate property

@property (nonatomic, assign) id<DVDelegate> myDelegat;

firstVC.m

backButton code for firstVC

- (IBAction)backButton_Click:(id)sender {
    NSLog(@"EEEEEE:%@",_DFCJ);
    if([_DFCJ isEqual:@"DL"]){
        NSLog(@"159");
        if([self.myDelegat respondsToSelector:@selector(DVViewControllerDismissed:)])
        {
            [self.myDelegat DVViewControllerDismissed:_DFCJ];//this method not call 
            NSLog(@"aPP");
        }
        [self dismissViewControllerAnimated:YES completion:nil];
        NSLog(@"5555");
    }
}


SecondVC.m

@interface DiamondListVC ()<DVDelegate>

receive below method

-(void)DVViewControllerDismissed:(NSString *)stringForFirst;{
    NSLog(@"AASASS");
   [self performSelector:@selector(callService) withObject:self afterDelay:0.1];
}

Result log

2018-04-21 09:33:39.382 search[907:16573] EEEEEE:DL
2018-04-21 09:33:39.382 search[907:16573] 159
2018-04-21 09:33:39.383 search[907:16573] 5555

but firstVC won't dismiss, please see my code and give me a suggestion.

Thanks in advance.


Solution

  • The reason why firstVC can't be dismissed because firstVC is pushed from secondVC, not presented.

    To pass data from firstVc to secondVc, you don't need to use delegate. You can get secondVC from firstVC by using self.navigationController.viewControllers.

    FirstVC.m

    - (IBAction)backButton_Click:(id)sender {
      NSLog(@"EEEEEE:%@",_DFCJ);
      if([_DFCJ isEqual:@"DL"]){
        NSLog(@"159");
    
        // Get |SecondVC| by using |self.navigationController.viewControllers|
        NSArray* viewControllers = [[self navigationController] viewControllers]; 
        SecondVC *previousViewController = viewControllers[viewControllers.count - 2]; 
        [previousViewController DVViewControllerDismissed:_DFCJ];
    
        [self.navigationController popViewControllerAnimated:YES];
        NSLog(@"5555");
      }
    }
    

    SecondVC.h

    @interface DiamondListVC : YourClass
    
    -(void)DVViewControllerDismissed:(NSString *)stringForFirst;
    
    @end