UIView continues to exist after removeFromSupervie

2019-05-11 16:02发布

问题:

I add a firstView in the AppDelegate :

#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];
}

Then I want to switch to the 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

And then the same thing for switching from secondView to firstView…

The problem is when I switch the view I thought to release is always visible and don't disappear.

Download the full code

回答1:

A better approach might be to create one top-level parent view controller that you add to the window. It should have a reference to both of your other view controllers and do the swapping instead. If you want your button inside each view to cause the swapping, you could just have your button IBAction for each post a notification that your top level view registers for and responds to.



回答2:

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

What is "self" here? And why does the MainViewController class have a property named mainViewController? Exploring those questions will likely lead you to the answer here.