I would like to present an instance of VC2
from an instance of VC1
and pass it a completion block to be executed when the VC2
dismisse
This is possible but you have to watch out for retain cycles. Remember that a block will capture any variables referenced within it including self. If VC1 keeps a strong reference to VC2 then be careful not to let the block have a strong reference to VC1 as well. If needed make a __weak
reference to self outside the block and use that.
See the Apple Documentation for more information about retain cycles using blocks and how to avoid them.
The easiest thing to do would be to subclass UIViewController and make your own methods and properties to achieve this.
You can declare a property to store a block as an instance variable like so:
@property (nonatomic, copy) dispatch_block_t completionBlock;
using the standard libdispatch block type.
Then define some methods for setting this up:
-(void)presentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(void (^)(void))completion dismissCompletion:(dispatch_block_t)dismissCompletion{
self.completionBlock = dismissCompletion;
[super presentViewController:viewController animated:animated completion:completion];
}
then override the dismiss method to call the completion block if there is one.
-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion{
if (self.completionBlock && ! completion){
[super dismissViewControllerAnimated:flag completion:self.completionBlock];
self.completionBlock = nil;
return;
}
[super dismissViewControllerAnimated:flag completion:completion];
}