Skip to content

Instantly share code, notes, and snippets.

@mayoff
Created August 10, 2013 05:52
Show Gist options
  • Save mayoff/6199244 to your computer and use it in GitHub Desktop.
Save mayoff/6199244 to your computer and use it in GitHub Desktop.
This is a generic implementation of prepareForSegue:sender: that calls a segue-specific method based on the segue identifier. There's also a similar implementation of shouldPerformSegueWithIdentifier:sender:.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSString *identifier = segue.identifier;
if (identifier.length == 0)
return;
NSString *selectorString = [NSString stringWithFormat:@"prepareFor%@Segue:sender:", identifier];
SEL selector = NSSelectorFromString(selectorString);
if (!selector || ![self respondsToSelector:selector])
return;
void (*method)(id, SEL, id, id) = (void (*)(id, SEL, id, id))[self methodForSelector:selector];
method(self, selector, segue, sender);
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
if (identifier.length == 0)
return YES;
NSString *selectorString = [NSString stringWithFormat:@"shouldPerform%@SegueWithSender:", identifier];
SEL selector = NSSelectorFromString(selectorString);
if (!selector || ![self respondsToSelector:selector])
return YES;
BOOL (*method)(id, SEL, id) = (BOOL (*)(id, SEL, id))[self methodForSelector:selector];
return method(self, selector, sender);
}
@mayoff
Copy link
Author

mayoff commented Aug 10, 2013

This implementation of prepareForSegue:sender: automatically calls a method specific to the segue. It constructs the segue-specific method name (selector) using the format prepareFor%@Segue:sender:, and substitutes the segue identifier for %@. So, for example, if you create a segue with the identifier DetailPushing, it will check for a method named prepareForDetailPushingSegue:sender: and call the method if it exists.

There is also a similar implementation of shouldPerformSegueWithIdentifier:sender:. It constructs the segue-specific method name using the format shouldPerform%@SegueWithSender:. It only passes the sender, and not the segue identifier, to the segue-specific method. So, for example, if you create a segue with the identifier DetailPushing, it will check for a method named shouldPerformDetailPushingSegueWithSender: and call the method if it exists. It will return whatever the segue-specific method returns. If it can't find a method-specific segue, it just returns YES.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment