views:

7158

answers:

2

Can anyone give me the example code that I can use to first present a modal view controller, then dismiss it? This is what I have been trying:

    NSLog(@"%@", blue.modalViewController);
    [blue presentModalViewController:red animated:YES];
    NSLog(@"%@", blue.modalViewController);
    [blue dismissModalViewControllerAnimated:YES];
    NSLog(@"%@", blue.modalViewController);
This code is in viewDidLoad ("blue" and "red" are both subclasses of UIViewController). I expect that I will show the red view and then immediately hide it, with some animation. However this peace of code only presents the modal view and does not dismiss it. Any idea? The first log shows "null" while the two other logs show <RedViewController: 0x3d21bf0>
Another point is, if I put this code in applicationDidFinishLaunching: the red view does not appear at all, and all logs get "null"

A: 

Your view-controllers are getting deallocated, perhaps you should retain them before presenting as modal. Have

[blue retain];
[red retain];

after creating them, to make sure they don't get released and deallocated before you use them.

luvieere
+4  A: 

First of all, when you put that code in applicationDidFinishLaunching, it might be the case that controllers instantiated from Interface Builder are not yet linked to your application (so "red" and "blue" are still nil).

But to answer your initial question, what you're doing wrong is that you're calling dismissModalViewControllerAnimated: on the wrong controller! It should be like this:

[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];

Usually the "red" controller should decide to dismiss himself at some point (maybe when a "cancel" button is clicked). Then the "red" controller could call the method on self:

[self dismissModalViewControllerAnimated:YES];

If it still doesn't work, it might have something to do with the fact that the controller is presented in an animation fashion, so you might not be allowed to dismiss the controller so soon after presenting it.

Tom van Zummeren
thanks, actually it's a problem with animation
phunehehe
According to the View Controller Programming guide for iPhone OS, this is incorrect when it comes to dismissing modal view controllers you should use delegation. So before presenting your modal view make yourself the delegate and then call the delegate from the modal view controller to dismiss.
OscarMk