我的内存管理应用程序出现问题。有一些我不明白的概念。例如,这个代码有什么问题?我应该如何处理这个问题?iPhone内存管理
CustomController.h:
@interface CustomController : UIViewController <UIScrollViewDelegate>
{
IBOutlet UIScrollView *scroll_view;
}
@property (nonatomic, retain) UIScrollView *scroll_view;
@end
CustomController.m:
@implementation CustomController
@synthesize scroll_view;
- (void)viewDidLoad
{
[self setup_content];
[super viewDidLoad];
}
- (void) setup_content
{
// Fill the scrollview with some subviews
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
[scroll_view release];
scroll_view = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[scroll_view release];
[super dealloc];
}
@end
使用它:
CustomController *custom_controller = [[CustomController alloc] initWithNibName: @"CustomController" bundle: nil];
NSLog(@"Controller: %i", [custom_controller retainCount]);
NSLog(@"ScrollView: %i", [custom_controller.scroll_view retainCount]);
[controllersArray addObject: custom_controller];
NSLog(@"Controller: %i", [custom_controller retainCount]);
NSLog(@"ScrollView: %i", [custom_controller.scroll_view retainCount]);
[custom_controller release];
NSLog(@"Controller: %i", [custom_controller retainCount]);
NSLog(@"ScrollView: %i", [custom_controller.scroll_view retainCount]);
和输出:
Controller: 1
ScrollView: 0
Controller: 2
ScrollView: 2
Controller: 1
ScrollView: 2
在这一点上,当我从数组中删除控制器,因为我不再需要它了,scrollView在控制器的dealloc方法中的retainCount是2,并且内存没有被释放(scrollView有很多未被存储的uiimageviews发布)。有人可以帮忙吗?
编辑:
最后的问题是,控制器视图正在由导航控制器保留。我正在使用控制器阵列作为自定义导航的堆栈。在弹出窗口中,我从阵列中移除了控制器,但导航控制器仍然保留了该视图。从超级视图中删除它可以解决问题,现在我的scrollView和它拥有的所有子视图都可以正确释放!谢谢大家!
不要调用** retainCount **。这对于调试这种东西来说是无用的。 – bbum 2011-04-20 16:07:38