I was looking at this question.
One of the answers shows how to use blocks to pass data backwards view the prepareForSegue
method. My understanding is t
In your view controller 1:
MyViewControllerClass2* vc2 = [[MyViewControllerClass2 alloc] initWithNibName:@"UIViewController" bundle:[NSBundle mainBundle] completion:^{
NSLog(@"view2 is closed");
}]];
[self.navigationController pushViewController:vc2 animated:YES];
In MyViewControllerClass2.m:
@interface MarryViewController ()
@property (nonatomic, copy) void(^completion)();
@end
@implementation MarryViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completion:(void(^)())completion
{
self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if( self )
{
//store completion block
_completion = completion;
}
return self;
}
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
//call completion block
_completion();
}
In MyViewControllerClass2.h:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completion:(void(^)())completion;
Just a few notes on how awesome block are:
MyViewControllerClass2 has no idea what is defined in _completion() which is the main point, as this is not of his concern
You could also call _completion() in -dealloc or even on some place where MyViewControllerClass2 will continue to run
You can pass arguments to block functions
You can pass arguments from block functions
Many more :)
I'm really encouraging people to get good overview on blocks and stat using them as they are pretty cool.
IMPORTANT!
While using block you do not declare delegate, the main idea and abstract result of delegate method and using block are the same. Moreover delegate pattern has it's advantages such as better documenting and more strictly usage. Still blocks are way more flexible and(when get used to) easier to use.
Regards,
hris.to