在removeFromSuperview之后,UIView仍然存在

时间:2009-10-03 16:31:09

标签: iphone memory-management uiview uiviewcontroller

我在AppDelegate中添加了firstView:

#import "TestViewAppDelegate.h"
#import "MainViewController.h"
@implementation TestViewAppDelegate

@synthesize window;
@synthesize mainViewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    MainViewController *aController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
    self.mainViewController = aController;
    [aController release];

    self.mainViewController.view.frame = [UIScreen mainScreen].applicationFrame;
    [window makeKeyAndVisible];
    [window addSubview:mainViewController.view];
}

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

然后我想切换到secondView:

#import "MainViewController.h"
#import "SecondViewController.h"

@implementation MainViewController

@synthesize mainViewController, secondViewController;

- (IBAction)viewSwitch
{
    SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];
    self.secondViewController = second;
    [second release];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.75];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];

    [mainViewController.view removeFromSuperview];
    [self.view addSubview:secondViewController.view];

    [UIView commitAnimations];
}

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

@end

然后从secondView切换到firstView同样的事情......

问题是,当我切换视图时,我认为释放始终可见并且不会消失。

Download the full code

2 个答案:

答案 0 :(得分:2)

[mainViewController.view removeFromSuperview];
[self.view addSubview:secondViewController.view];

这里的“自我”是什么?为什么MainViewController类有一个名为mainViewController的属性?探索这些问题可能会引导您找到答案。

答案 1 :(得分:1)

更好的方法可能是创建一个添加到窗口的顶级父视图控制器。它应该引用两个其他视图控制器并进行交换。如果您希望每个视图中的按钮都能进行交换,您可以在每个帖子上按下IBAction按钮,以获得您的顶级视图注册并响应的通知。