Search code examples
iosobjective-csegueuistoryboardsegueunwind-segue

How to use PerformSegueForIdentifier


I am fresh in iOS and objective-c. I am learning how to use segues, especially unwind segue.

while reading, I got a bit confused about the usage of 'shouldPerformSegueForIdentifier' and 'performSegueForIdentifier'.

I created an example contains two 'ViewControllers', 'ViewController.m' as shown in the code posted below 'VC_1' and 'ServiceViewController'

my questions are:

-when and how should I use 'performSegueForIdentifier'

-when and how should I use 'shouldIPerformSegueForIdentifier'?

VC_1:

#import "ViewController.h"
#import "ServiceViewController.h"

@interface ViewController ()

@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)btnStartService:(UIButton *)sender {
   if (sender.tag == 1) {
    NSLog(@"CLICKED");

    [self performSegueWithIdentifier:@"seguePassInterval" sender:(id)   
sender];
}
}

-(IBAction)btnExitApp:(UIButton *)sender {
    NSLog(@"EXIT_CLICKED");

}



 - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"seguePassInterval"]) {
    ((ServiceViewController*)segue.destinationViewController).data = @"testData"; //passing data to destinationViewController of type "TestViewController"
    NSLog(@"SEGUE");
}

}


@end

img

enter image description here


Solution

  • The prepareForSegue method is called right before the segue is executed, and allow to pass data between ViewController among other things, you can by example check if the identifier of your segue is "XxX" and pass some data or if is "YYY" call for a method

    - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
    {
        if ([segue.identifier isEqualToString:@"seguePassInterval"]) {
        ((TestViewController*)segue.destinationViewController).data = @"testData"; //passing data to destinationViewController of type "TestViewController"
        NSLog(@"SEGUE");
    }
    }
    

    method performSegueWithIdentifier is used to as his name says execute a segue using his identifier, you can perform a segue when you need it

    and finally shouldPerformSegue is used to avoid perform a segue if your app is in some state, for example if you don't have the destinationViewController data yet you can return false until you get that

    Hope this helps