Skip to content

Instantly share code, notes, and snippets.

@oliverbarreto
Created December 5, 2013 23:15
Show Gist options
  • Save oliverbarreto/7815810 to your computer and use it in GitHub Desktop.
Save oliverbarreto/7815810 to your computer and use it in GitHub Desktop.
Blocks for Presenting and Dismissing View Controllers instead of Protocols and Delegate callbacks
DETAIL VIEW CONTROLLER - PRESENTED VC
#instead of defining the protocol with its required callback methods and delegate property
# DetailViewController.h
typedef void (^DetailViewControllerCompletionBlock)(BOOL success);
@property (nonatomic, copy) DetailViewControllerCompletionBlock completionBlock;
# Instead of falling delegate call cakes from IBActions asociares with UI buttons... Assign the BOOL variable of the block
# DetailViewController.m
- (IBAction)cancel:(id)sender {
if (self.completionBlock != nil) self.completionBlock(NO);
}
- (IBAction)done:(id)sender {
...
if (self.completionBlock != nil) self.completionBlock(YES);
#MASTER VIEW CONTROLLER - PRESENTER VC
# Remove the protocol conforming statement and change prepare for segue...
# What you did here is move the contents from detailViewControllerDidCancel: and detailViewControllerDidClose: into the prepareForSegue:.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"ShowDetail"]) {
// 0. Get the Destination VC as usual
DetailViewController *controller = segue.destinationViewController;
// 1. Pass the Block that will be executed instead of the delegate callbacks
controller.completionBlock = ^(BOOL success)
{
// If "Done Button" was pressed (success=YES); No thing is done in case that "Cancel Button" was pressed (success=NO)
if (success) {
// Save DATA from the detail VS into the model to save changes since success receives the "Done button"
}
// Dissmiss the DetailVC
[self dismissViewControllerAnimated:YES completion:nil];
};
// 2.Do what you must do to prepare the segue to fire the destination VC here
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment