obj-c presentmodalviewcontroller.. Where to release
I have an app that switches around to about 10 different view controllers with methods like this:
-(IBAction)pg2button{
pg2 *pg2view = [[pg2 alloc] initWithNibName: nil bundle: nil];
pg2view.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:pg2view animated:YES];
[pg2view release];
}
Where is a good pl开发者_开发百科ace to release the current view before the next one is presented? Thanks!
(1) Format your question: add at least 4 spaces before each code line.
(2) Why do you use initWithNibName:bundle:
initializer if you pass nil as NIB name?
Just use the regular init
.
(3) I see that you already release the view controller.
It will be released one more time (in the background) once you will dismiss it.
(4) If you've meant to ask "Where is a good place to dismiss the current view before the next one is presented?" then it depends on your structure.
Usually, the best approach is to add a delegate method in the original view controller, the modal view controller will call that delegate method and the original view controller will dismiss the modal one like this: [self dismissModalViewControllerAnimated:YES];
.
EDIT:
Code sample for the delegate:
// The protocol that your original view controller should implement
@protocol ModalViewControllerDelegate <NSObject>
@required
- (void)modalViewControllerDidCancel:(UIViewController *)modalViewController;
- (void)modalViewController:(UIViewController *)modalViewController didReturnWithResult:(NSObject)result;
@end
This is how to implement:
@interface MainViewController : UIViewController <ModalViewControllerDelegate> {
...
}
...
@end
@implementation MainViewController
...
#pragma mark -
#pragma mark ModalViewControllerDelegate methods
- (void)modalViewControllerDidCancel:(UIViewController *)modalViewController {
[self dismissModalViewControllerAnimated:YES];
}
- (void)modalViewController:(UIViewController *)modalViewController didReturnWithResult:(NSObject)result {
// TODO: Do something with the result
[self dismissModalViewControllerAnimated:YES];
}
...
@end
You should add the next code to your modal view controllers:
@interface ModalViewController1 : UIViewController {
...
id<ModalViewControllerDelegate> delegate;
...
}
@property (assign) id<ModalViewControllerDelegate> delegate;
...
@end
@implementation ModalViewController1
@synthesize delegate;
...
- (void)cancelUserAction {
...
[self.delegate modalViewControllerDidCancel:self];
}
@end
Don't forget also to set the delegate property to self (from MainViewController) once you create the modal view controller...
精彩评论