obj-c presentmodalviewcontroller ..在哪里发布

时间:2010-07-19 06:06:47

标签: iphone objective-c

我有一个应用程序可以使用以下方法切换到大约10个不同的视图控制器:

 -(IBAction)pg2button{
      pg2 *pg2view = [[pg2 alloc] initWithNibName: nil bundle: nil];
      pg2view.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
      [self presentModalViewController:pg2view animated:YES];
      [pg2view release];
  }

在呈现下一个视图之前,在哪里发布当前视图的好地方? 谢谢!

1 个答案:

答案 0 :(得分:2)

(1)格式化你的问题:在每个代码行之前添加至少4个空格。

(2)如果你将nil作为NIB名称传递n,为什么要使用initWithNibName:bundle:初始值设定项? 只需使用常规init

(3)我看到你已经释放了视图控制器 一旦你解雇它,它将再次被释放(在后台)。

(4)如果您打算在下一个呈现之前询问“解雇当前观点的好地方在哪里?”那取决于你的结构。
通常,最好的方法是在原始视图控制器中添加委托方法,模态视图控制器将调用该委托方法,原始视图控制器将忽略模态,如下所示:[self dismissModalViewControllerAnimated:YES];

修改的:
代表的代码示例:

// 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

这是如何实现:

@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

您应该将下一个代码添加到模态视图控制器中:

@interface ModalViewController1 : UIViewController {

    ...

    id<ModalViewControllerDelegate> delegate;

    ...

}

@property (assign) id<ModalViewControllerDelegate> delegate;

...

@end


@implementation ModalViewController1

@synthesize delegate;

...

- (void)cancelUserAction {

    ...

    [self.delegate modalViewControllerDidCancel:self];
}

@end

一,创建模态视图控制器后,不要忘记将委托属性设置为self(来自MainViewController)...