tabBarController内存泄漏

时间:2010-01-16 21:31:05

标签: iphone memory-leaks uitabbarcontroller nsarray

在我的AppDelegate中,我启动了一个tabBar控制器,其中添加了一堆navigationController作为选项卡。我使用以下代码:

// Init tabBar Controller
tabBarController = [[[UITabBarController alloc] init] retain];

// Init Root Views of navigation controllers
FirstRootViewController* firstViewController = [[[FirstRootViewController alloc] init] autorelease];
SecondRootViewController* secondViewController = [[[SecondRootViewController alloc] init] autorelease];
ThirdRootViewController* thirdViewController = [[[ThirdRootViewController alloc] init] autorelease];

// Init Navigation controllers of tabs
UINavigationController* firstNavController = [[[UINavigationController alloc] initWithRootViewController:firstViewController] autorelease];
UINavigationController* secondNavController = [[[UINavigationController alloc] initWithRootViewController:secondViewController] autorelease];
UINavigationController* thirdNavController = [[[UINavigationController alloc] initWithRootViewController:thirdViewController] autorelease];

firstNavController.navigationBar.barStyle = UIBarStyleBlack;
secondNavController.navigationBar.barStyle = UIBarStyleBlack;
thirdNavController.navigationBar.barStyle = UIBarStyleBlack;

// Create array for tabBarController and add navigation controllers to tabBarController
NSArray *navigationControllers = [NSArray arrayWithObjects:firstNavController, secondNavController, thirdNavController, nil];
tabBarController.viewControllers = navigationControllers;
[window addSubview:tabBarController.view];

dealloc功能:

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

firstNavController是要添加的导航控制器,它们在几行之后完全正确释放(它们是使用alloc创建的)。

TabBarController是一个类变量,它是使用@property(nonatomic,retain)和@synthesize tabBarController创建的。它在dealloc方法中接收一个release命令。

现在乐器告诉我,“tabBarController.viewControllers = navigationController”就行了两次内存泄漏。

我折磨了我的头,但我不明白为什么:根据我的理解,navigationControllers应该自动释放,如果我稍后发送一个释放命令,应用程序崩溃,所以我想我是对的。

任何猜测都错了吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

首先,您的tabBarController类变量的引用计数增加了两倍。一次来自alloc,一次来自代码第一行的retain,但只在dealloc中发布一次。这可能是您的内存泄漏的来源。

其次,尽管您已声明匹配的@property(nonatomic, retain) tabBarController(并通过@sysnthesize实现),但您实际上并未使用属性访问器(以及在分配期间其相应的保留和释放行为)为此您执行此操作需要使用self.tabBarController而不仅仅是tabBarController,它将引用类变量,而不是属性。

尝试将代码修改为以下内容以查看是否可以解决您的问题

// Init tabBar Controller
UITabBarController* tbc = [[[UITabBarController alloc] init];
self.tabBarController = tbc;
[tbc release];
...

- (void)dealloc {
[window release];
self.tabBarController = nil;
[super dealloc]; }