Aug 2012 Update:
iOS 5 and greater have introduced safer APIs for doing things after modals have animated into / out of place using completion blocks:
[self presentViewController:myModalVC animated:YES completion:^{}];
[self dismissViewControllerAnimated:YES completion:^{}];
Pre-Aug 2012 Answer:
I encountered a similar problem when dismissing modal one and then presenting modal two in rapid succession. Sometimes modal two would show after the modal one was dismissed and sometimes modal two wouldn't appear at all and that made me very sad.
Looks like a race condition to me...
Putting a 1+ second delay on the caller of the method that presented modal two, showModalTwo
, made modal two appear every time after modal one was dismissed:
- (void)didDismissModalOne {
[self performSelector:@selector(showModalTwo:)
withObject:someNumber
afterDelay:1.0f];
}
This confirmed a suspicion that there was some sort of race condition between the dismissal of modal one and the presentation of modal two. Putting a delay on the caller, however, is inelegant and did not guarantee that the race condition wouldn't re-appear under other circumstances.
The problem
Turns out that UIViewController
s have a public property, modalViewController
, that gets set up when presentModalViewController:animated:
is called and torn down when dismissModalViewControllerAnimated:
is called. The catch is that it doesn't get torn down synchronously, so it's possible to create a race between removing the old value of modalViewController
and setting up a new value in the following way.
- Present modal one.
myViewController.modalViewController
now points to modal one
- Dismiss modal one. Background process to tear down
myViewController.modalViewController
has started, but myViewController.modalViewController
the still points to modal one
- Present modal two,
myViewController.modalViewController]
now points to modal two
- System callback fires, setting
myViewController.modalViewController
to nil
, this interrupts the process of modal two animating in and the result is the user never sees it.
The race starts on step 2 and manifests on step 4.
The solution
My solution was to put a guard condition on the method that presented modal two to ensure that myViewControoler.modalViewController
was nil
before attempting to present modal two.
-(void)showModalTwo:(NSNumber *)aParameter {
if (self.modalViewController) {
[self performSelector:@selector(showModalTwo:)
withObject:aParameter
afterDelay:0.1f];
return;
}
// You can now present the second modal safely.
}
Worked like a charm. A more elegant solution might include a timeout.
Post script
I really didn't like the polling aspect of this solution. @Nimrod suggests, in the accepted answer to this question, that you can safely initiate the presentation of modal two from the viewDidDisappear:
method of modal one. I liked the sound of this event driven approach, but after doing a full implementation in my use case I confirmed that the race condition persisted when presenting modal two using a callback inside viewDidDisappear:
. The only way to be absolutely sure that modal two will be presented is to poll inside the parent view controller until you're absolutely sure that self.modalViewController
is nil
. Then and only then is it "safe" to pop modal two.
This question seems to be very popular here on Stack Overflow so I thought I would try and give a better answer to help out people starting in the world of iOS like me.
I hope this answer is clear enough for people to understand and that I have not missed anything.
Passing Data Forward
Passing data forward to a view controller from another view controller. You would use this method if you wanted to pass an object/value from one view controller to another view controller that you may be pushing on to a navigation stack.
For this example, we will have ViewControllerA
and ViewControllerB
To pass a BOOL
value from ViewControllerA
to ViewControllerB
we would do the following.
in ViewControllerB.h
create a property for the BOOL
@property (nonatomic, assign) BOOL isSomethingEnabled;
in ViewControllerA
you need to tell it about ViewControllerB
so use an
#import "ViewControllerB.h"
Then where you want to load the view, for example, didSelectRowAtIndex
or some IBAction
, you need to set the property in ViewControllerB
before you push it onto the navigation stack.
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.isSomethingEnabled = YES;
[self pushViewController:viewControllerB animated:YES];
This will set isSomethingEnabled
in ViewControllerB
to BOOL
value YES
.
Passing Data Forward using Segues
If you are using Storyboards you are most likely using segues and will need this procedure to pass data forward. This is similar to the above but instead of passing the data before you push the view controller, you use a method called
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
So to pass a BOOL
from ViewControllerA
to ViewControllerB
we would do the following:
in ViewControllerB.h
create a property for the BOOL
@property (nonatomic, assign) BOOL isSomethingEnabled;
in ViewControllerA
you need to tell it about ViewControllerB
, so use an
#import "ViewControllerB.h"
Create the segue from ViewControllerA
to ViewControllerB
on the storyboard and give it an identifier. In this example we'll call it "showDetailSegue"
Next, we need to add the method to ViewControllerA
that is called when any segue is performed. Because of this we need to detect which segue was called and then do something. In our example, we will check for "showDetailSegue"
and if that's performed, we will pass our BOOL
value to ViewControllerB
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"showDetailSegue"]){
ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
controller.isSomethingEnabled = YES;
}
}
If you have your views embedded in a navigation controller, you need to change the method above slightly to the following
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"showDetailSegue"]){
UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
ViewControllerB *controller = (ViewControllerB *)navController.topViewController;
controller.isSomethingEnabled = YES;
}
}
This will set isSomethingEnabled
in ViewControllerB
to BOOL
value YES
.
Passing Data Back
To pass data back from ViewControllerB
to ViewControllerA
you need to use Protocols and Delegates or Blocks, the latter can be used as a loosely coupled mechanism for callbacks.
To do this we will make ViewControllerA
a delegate of ViewControllerB
. This allows ViewControllerB
to send a message back to ViewControllerA
enabling us to send data back.
For ViewControllerA
to be a delegate of ViewControllerB
it must conform to ViewControllerB
's protocol which we have to specify. This tells ViewControllerA
which methods it must implement.
In ViewControllerB.h
, below the #import
, but above @interface
you specify the protocol.
@class ViewControllerB;
@protocol ViewControllerBDelegate <NSObject>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
@end
Next still in the ViewControllerB.h
, you need to set up a delegate
property and synthesize in ViewControllerB.m
@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;
In ViewControllerB
we call a message on the delegate
when we pop the view controller.
NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];
That's it for ViewControllerB
. Now in ViewControllerA.h
, tell ViewControllerA
to import ViewControllerB
and conform to its protocol.
#import "ViewControllerB.h"
@interface ViewControllerA : UIViewController <ViewControllerBDelegate>
In ViewControllerA.m
implement the following method from our protocol
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item
{
NSLog(@"This was returned from ViewControllerB %@", item);
}
Before pushing viewControllerB
to navigation stack we need to tell ViewControllerB
that ViewControllerA
is its delegate, otherwise we will get an error.
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.delegate = self
[[self navigationController] pushViewController:viewControllerB animated:YES];
References
- Using Delegation to Communicate With Other View Controllers in the View Controller Programming Guide
- Delegate Pattern
NSNotification center
It's another way to pass data.
// Add an observer in controller(s) where you want to receive data
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeepLinking:) name:@"handleDeepLinking" object:nil];
-(void) handleDeepLinking:(NSNotification *) notification {
id someObject = notification.object // Some custom object that was passed with notification fire.
}
// Post notification
id someObject;
[NSNotificationCenter.defaultCenter postNotificationName:@"handleDeepLinking" object:someObject];
Passing Data back from one class to another (A class can be any controller, Network/session manager, UIView subclass or any other class)
Blocks are anonymous functions.
This example passes data from Controller B to Controller A
Define a block
@property void(^selectedVoucherBlock)(NSString *); // in ContollerA.h
Add block handler (listener)
Where you need a value (for example, you need your API response in ControllerA or you need ContorllerB data on A)
// In ContollerA.m
- (void)viewDidLoad {
[super viewDidLoad];
__unsafe_unretained typeof(self) weakSelf = self;
self.selectedVoucherBlock = ^(NSString *voucher) {
weakSelf->someLabel.text = voucher;
};
}
Go to Controller B
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ControllerB *vc = [storyboard instantiateViewControllerWithIdentifier:@"ControllerB"];
vc.sourceVC = self;
[self.navigationController pushViewController:vc animated:NO];
Fire block
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath {
NSString *voucher = vouchersArray[indexPath.row];
if (sourceVC.selectVoucherBlock) {
sourceVC.selectVoucherBlock(voucher);
}
[self.navigationController popToViewController:sourceVC animated:YES];
}
Another Working Example for Blocks
Best Answer
I realise this is a late answer but maybe this will help someone else looking for a solution to this, here is what I did:
For me, i found that line of code was being called multiple times, I couldn't find out why so this was the easiest fix.