Why am I getting a memory leak when adding a button as a subtitle?

I have an application that uses tableview, as well as UIButton, which I add as a slave for each user cell, for example:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; checkButton = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(2.0, 2.0, 40.0, 40.0)]; [cell.contentView addSubview:checkButton]; // lot of other code return cell; } 

I thought that everything was in order until I started using the Tools to make sure that I did not have memory leaks, but I found that adding UIButton as a cell spy somehow caused a leak inside UIKit.

In particular, I get a memory leak for each row of cells (every time the button is added as a preview), and the leaked object is "CALayer", and the responsible frame is "[UIView _createLayerWithFrame:]".

Am I doing something wrong here?

+4
source share
3 answers

The code method [UIButton buttonWithType] already includes the initWithFrame method. You just need to use CGRectMake and then set the button frame.

 rectangle = CGRectMake(2.0f,2.0f,40.0f,40.0f); checkButton = [UIButton buttonWithType:UIButtonTypeCustom]; checkButton.frame = rectangle; 
+5
source

Have you tested this on a physical device or simulator?

It is known that the simulator has some variations in memory management compared to the actual device code. You should always run memory leak tests on a real device.

Otherwise, your code looks correct to me.

0
source

Is checkButton a @property (persistence) of your class?

Because in this case you must set the null property after use ... but you cannot, because the cell's life cycle is not under your control; you will be better off with a local variable.

Also, after adding addSubview, you should put [checkButton release], since the addSubview code has its own hold / release

0
source

Source: https://habr.com/ru/post/1302065/


All Articles