【发布时间】:2011-10-03 16:41:07
【问题描述】:
我正在开发一个应用程序,该应用程序的主视图希望在触摸按钮时生成子视图。因此,当我收到按钮事件时,MainViewController 通过调用 initWithNibName 并将 ChildViewController 存储在 ivar 中来生成子视图。然后我通过附加动画并设置 childVC.view.hidden = NO 来显示 ChildView。
这可行,但我注意到 ChildViewController 在关闭 ChildView 后从未被释放。当我第一次访问子视图时,我意识到 ChildVC 的保留计数从 1 变为 2。因此,nib 加载内容中的某些内容似乎再次保留了我的 ChildVC(除了我在对象初始化期间期望的初始保留)。
谁能帮我弄清楚为什么 ChildVC 被保留了额外的时间,当我想关闭子视图时如何确保它被完全释放?
编辑:这里有一些代码,只是稍微简化了一点。这些是父视图控制器上的方法。
-(IBAction)onLaunchChildButtonTouched:(id)sender
{
m_childViewController = [[ChildViewController alloc] initWithNibName:@"ChildViewController" bundle:nil];
[m_childViewController setParentDelegate:self]; // this is a weak reference
// m_childViewController retain count here is 1, as expected
m_childViewController.view.hidden = YES;
// m_childViewController retain count is now 2, not expected
[self.view addSubview:m_childViewController.view];
[self addTransitionEntrDir:YES]; // code omitted
m_childViewController.view.hidden = NO;
}
-(void)onChildWantsToClose:(id)child
{
NSAssert( child == m_childViewController, @"unexpected childVC" );
// if child view is now hidden, we should remove it.
if( m_childViewController != nil && m_childViewController.view.hidden )
{
[m_childViewController.view removeFromSuperview];
[m_childViewController release]; m_childViewController = nil;
// BUG: m_childViewController retain count is still 1 here, so it never gets released
}
}
【问题讨论】:
-
可能会显示您的实际代码?
-
显示一些代码将有助于将 A 带入这个 Q。
-
用一些代码更新了原始帖子。
标签: iphone objective-c memory-leaks