gpt4 book ai didi

Iphone:无法从 UITabBarController 加载模态视图

转载 作者:行者123 更新时间:2023-12-03 21:13:15 25 4
gpt4 key购买 nike

我希望能够使用 UIViewController 的实例呈现模态视图。当从标准 UIViewController ( Root View )呈现它时,我这样做没有问题。我已经设置了一个委托(delegate)来使呈现的 Root View 关闭模态视图。这是根据 Apple 最佳实践的。

当我尝试在从 UITabBarController 加载 Root View 时使相同的 Root View 呈现模态视图时,我遇到了严重的问题。前三次我加载 View 没有问题,但第四次调试器显示在尝试调用委托(delegate)方法时 Root View 已被释放(“消息发送到已释放的实例”)。我的猜测是,在显示模态视图时, Root View 已自动释放。我怎样才能避免这种情况?

我设置的示例使用 UITabBarController 的模板,从第一个 View 呈现模态视图:

FirstViewController.h( Root View Controller ):

#import <UIKit/UIKit.h>

@protocol ModalDelegate;
@interface FirstViewController : UIViewController <ModalDelegate>{
}

-(IBAction)startPressed:(id)sender;
@end

FirstViewController.m:

#import "FirstViewController.h"
#import "ModalViewController.h"


@implementation FirstViewController

-(IBAction)startPressed:(id)sender
{
ModalViewController *modal=[[ModalViewController alloc] init];
modal.delegate=self;
[self presentModalViewController:modal animated:TRUE];
[modal release];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

- (void)dealloc {
[super dealloc];
}

#pragma mark Modal Delegate
-(void)modal:(ModalViewController *)controller
{
[self dismissModalViewControllerAnimated:YES];
}

@end

ModalViewController.h:

#import <UIKit/UIKit.h>

@protocol ModalDelegate;


@interface ModalViewController : UIViewController {
id<ModalDelegate> delegate;

}

@property (assign) id<ModalDelegate> delegate;

- (IBAction)OKPressed:(id)sender;

@end

@protocol ModalDelegate <NSObject>

@optional
-(void)modal:(ModalViewController *)controller;

@end

ModalViewController.m:

#import "ModalViewController.h"

@implementation ModalViewController
@synthesize delegate;
- (IBAction)OKPressed:(id)sender
{
if ([self.delegate respondsToSelector:@selector(modal:)]) //Check to see if method responds to selector
{
[self.delegate modal:self];
}
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

- (void)dealloc {
[delegate release];
[super dealloc];
}

@end

最佳答案

您不应该在 ModalViewController 的 dealloc 实现中释放委托(delegate),因为您(正确地)没有保留它。

此外,您可以关闭模​​态 View Controller 本身,而不是设置委托(delegate)。我觉得这个更简单。这是 iPhone 开发中心对 dismissModalViewControllerAnimated: 的讨论

The parent view controller is responsible for dismissing the modal view controller it presented using the presentModalViewController:animated: method. If you call this method on the modal view controller itself, however, the modal view controller automatically forwards the message to its parent view controller.

关于Iphone:无法从 UITabBarController 加载模态视图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1455966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com