Shaokan Shaokan - 1 year ago 116
Objective-C Question

UICollectionView Iteration over cells - memory warning

After doing some debug, I've found that the following code makes my application's memory usage grow constantly until the application crashes. When I start the application, the memory usage is around 2MB, then when I keep scrolling back and forth it continues to grow. When I stop scrolling for a second, the memory usage decreases (not critically though, for example from 50M to 35M). Please have a look at why I have:

This is happening in my custom UICollectionViewController subclass:

for (myAppCell *cell in [self.collectionView visibleCells])
UILabel *label [[UILabel alloc] initWithFrame:CGRectMake(10, 10, cell.frame.size.width, cell.frame.size.height)];
label.text = @"Hello World!";

[cell.contentView addSubview:label];

Now here are the observations that I made while debugging:

  1. If I comment all of the code inside the for block, and scroll back and forth for an infinite time the application memory is stable at 2.1MB (in this case it continues to loop but does actually nothing inside - therefore the problem must be with the allocation of UILabel).

  2. I tried to check the subviews count of both the collection view and cells and they are respectively 14 and 1 (as it should be - so the problem is not the accumulation of subviews I believe).

  3. ARC is on.

  4. Edit: Actually, the problem occurs only when I add the UILabel to the cell. When I comment the last line (
    [cell.contentView addSubview:label
    ) the application runs normally as well. Therefore it must be this line.

  5. Edit: By the way I am not removing the cells once they are invisible (I do not know how to do, and If I actually need to do, I am pretty new to iOs programming).

Now I did not post the remaning of the code because as I said when I comment out the inner block the applications runs normally - that is, it creates my cells and when I scroll there is no problem (memory remains at 2.1MB).

What could be the problem?


This code is located in my
method. It is called from

Answer Source

Because whenever you scrolling the collection view you adding UILable again and again to that view. this will increase the memory. You can simply remove the all existing views from that cell before adding new views.

Use this code to remove all subviews

 [[cell.contentView subviews]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download