PushViewController:这是内存泄漏吗?

时间:2011-12-30 08:14:36

标签: iphone objective-c ios memory-leaks

我正在开发一个带有最新SDK和XCode 4.2的iOS 4(我使用 ARC )。

我正在以编程方式开发导航控制器,我有一个问题。

这是AppDelegate.h

#import <UIKit/UIKit.h>

@class ViewController;
@class SecondViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    UINavigationController* navController;
    ViewController* viewController;
    SecondViewController* secondViewController;
}

@property (strong, nonatomic) UIWindow *window;

- (void) showSecondViewController;

@end

这是AppDelegate.m

    #import "AppDelegate.h"

    #import "ViewController.h"
    #import "SecondViewController.h"

    @implementation AppDelegate

    @synthesize window = _window;

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
        viewController.title = @"Menu";
        navController = [[UINavigationController alloc] initWithRootViewController:viewController];
        navController.navigationBar.tintColor = [UIColor blackColor];
        self.window.rootViewController = navController;

        [self.window makeKeyAndVisible];
        return YES;
    }

- (void) dealloc
{
   [_window release];
   [viewController release];
   [navController release];
   [secondViewController release];
}
    - (void)applicationWillResignActive:(UIApplication *)application
    {
        ...
    }

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        ...
    }

    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        ...
    }

    - (void)applicationDidBecomeActive:(UIApplication *)application
    {
        ...
    }

    - (void)applicationWillTerminate:(UIApplication *)application
    {
        ...
    }

    - (void) showSecondViewController
    {
        secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
        secondViewController.title = @"Second";
        [navController pushViewController:secondViewController animated:YES];
    }

我的问题是关于最后一种方法-(void)showSecondViewController;

我可以在最后添加这一行吗?

[secondViewController release]

我已经分析了应用程序,我没有看到任何内存泄漏。但我必须在这里问一下,因为我不确定。

1 个答案:

答案 0 :(得分:1)

如果再次调用showSecondViewController方法,将会出现内存泄漏。

您应该在secondViewController方法中发布showSecondViewController

- (void) showSecondViewController
{
    secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    secondViewController.title = @"Second";
    [navController pushViewController:secondViewController animated:YES];
    [secondViewController release]
}

当您执行navController

时,pushViewController:secondViewController会自动保留它