How to check if a view controller can perform a segue
To check whether the segue existed or not, I simply surrounded the call with a try-and-catch block. Please see the code example below:
@try { [self performSegueWithIdentifier:[dictionary valueForKey:@"segue"] sender:self];}@catch (NSException *exception) { NSLog(@"Segue not found: %@", exception);}
Hope this helps.
- (BOOL)canPerformSegueWithIdentifier:(NSString *)identifier{ NSArray *segueTemplates = [self valueForKey:@"storyboardSegueTemplates"]; NSArray *filteredArray = [segueTemplates filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"identifier = %@", identifier]]; return filteredArray.count>0;}
This post has been updated for Swift 4.
Here is a more correct Swift way to check if a segue exists:
extension UIViewController {func canPerformSegue(withIdentifier id: String) -> Bool { guard let segues = self.value(forKey: "storyboardSegueTemplates") as? [NSObject] else { return false } return segues.first { $0.value(forKey: "identifier") as? String == id } != nil } /// Performs segue with passed identifier, if self can perform it. func performSegueIfPossible(id: String?, sender: AnyObject? = nil) { guard let id = id, canPerformSegue(withIdentifier: id) else { return } self.performSegue(withIdentifier: id, sender: sender) }}// 1if canPerformSegue("test") { performSegueIfPossible(id: "test") // or with sender: , sender: ...)}// 2performSegueIfPossible(id: "test") // or with sender: , sender: ...)