我以编程方式设置了一个带有 2 个按钮的 UINavigationBar。
-(void)setUpNavigationBar{
//The Navbar
UIImage *backgroundImage = [UIImage imageNamed:@"top_bar_gradient"];
UINavigationBar *naviBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, MAINBAR_WIDTH, MAINBAR_HEIGHT)];
[naviBar setTintColor:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0]];
[naviBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
//Right Button
UIButton *rButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *rButImage = [UIImage imageNamed:@"top_icon_menu2"];
[rButton setBackgroundImage:rButImage forState:UIControlStateNormal];
[rButton addTarget: self.viewDeckController action:@selector(toggleRightView) forControlEvents:UIControlEventTouchUpInside];
[rButton setFrame:CGRectMake(MAINBAR_BUTTON_X, MAINBAR_BUTTON_Y, MAINBAR_BUTTON_WIDTH, MAINBAR_BUTTON_HEIGHT)];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithCustomView:rButton];
//Left Button
UIButton *lButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *lButImage = [UIImage imageNamed:@"top_icon_menu1"];
[lButton setBackgroundImage:lButImage forState:UIControlStateNormal];
[lButton addTarget: self.viewDeckController action:@selector(toggleLeftView) forControlEvents:UIControlEventTouchUpInside];
[lButton setFrame:CGRectMake(MAINBAR_BUTTON_X, MAINBAR_BUTTON_Y, MAINBAR_BUTTON_WIDTH, MAINBAR_BUTTON_HEIGHT)];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithCustomView:lButton];
//Put it all together
naviBarItem.leftBarButtonItem = leftButton;
naviBarItem.rightBarButtonItem = rightButton;
naviBar.items = [NSArray arrayWithObjects:naviBarItem,nil];
self.navigationItem.leftBarButtonItem = leftButton;
[self.view addSubview:naviBar];
// This was my approach preventing the heap growth.
rightButton = nil;
leftButton = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self setUpNavigationBar];
}
我现在通过仪器分析应用程序并在 XCode 5 中拍摄 Heapshots(它们被称为“Generations”)。我想首先解决我自己的对象的问题,并希望其他堆增长问题只是从我自己的对象“级联”。
所以我看到有 UIBarButtonItem 每次我关闭和打开应用程序时都会将堆增加 448 字节(这是我拍摄堆后的例程)。由于有 4 个对象活着,似乎这些对象没有被释放,我正在使用ARC
问题是每次关闭和打开应用程序时,我的堆都会增长大约 200 kb。这是内存泄漏:
setUpNavigationBar
深入挖掘我发现它是我函数中的 UIBarButtonItem 。
所以我的问题是如何防止这里的内存泄漏?由于启用了 ARC,我无法自己释放该对象。