objective-ciosios5uistoryboardsegue

How to check if a view controller can perform a segue


This might be a very simple question but didn't yield any results when searching for it so here it is...

I am trying to work out a way to check if a certain view controller can perform a segue with identifier XYZ before calling the performSegueWithIdentifier: method.

Something along the lines of:

if ([self canPerformSegueWithIdentifier:@"SegueID"])
    [self performSegueWithIdentifier:@"SegueID"];

Possible?


Solution

  • As stated in the documentation:

    Apps normally do not need to trigger segues directly. Instead, you configure an object in Interface Builder associated with the view controller, such as a control embedded in its view hierarchy, to trigger the segue. However, you can call this method to trigger a segue programmatically, perhaps in response to some action that cannot be specified in the storyboard resource file. For example, you might call it from a custom action handler used to process shake or accelerometer events.

    The view controller that receives this message must have been loaded from a storyboard. If the view controller does not have an associated storyboard, perhaps because you allocated and initialized it yourself, this method throws an exception.

    That being said, when you trigger the segue, normally it's because it's assumed that the UIViewController will be able to respond to it with a specific segue's identifier. I also agree with Dan F, you should try to avoid situations where an exception could be thrown. As the reason for you not to be able to do something like this:

    if ([self canPerformSegueWithIdentifier:@"SegueID"])
        [self performSegueWithIdentifier:@"SegueID"];
    

    I am guessing that:

    1. respondsToSelector: only checks if you are able to handle that message in runtime. In this case you can, because the class UIViewController is able to respond to performSegueWithIdentifier:sender:. To actually check if a method is able to handle a message with certain parameters, I guess it would be impossible, because in order to determine if it's possible it has to actually run it and when doing that the NSInvalidArgumentException will rise.
    2. To actually create what you suggested, it would be helpful to receive a list of segue's id that the UIViewController is associated with. From the UIViewController documentation, I wasn't able to find anything that looks like that

    As for now, I am guessing your best bet it's to keep going with the @try @catch @finally.