自定义UICollectionViewCell增加了内存分配

时间:2013-12-21 13:27:08

标签: ios uicollectionview

完成我的应用程序后,我意识到内存分配非常庞大。 我想我已经将问题分离到了一个使用UICollectionView的视图。 集合视图具有自定义cell

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 12;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

 MyCollectionCell *yearCell = [collectionView dequeueReusableCellWithReuseIdentifier:myCellIdentifier forIndexPath:indexPath];
if (yearCell ==  nil)
    yearCell = [[AgendaYearCollectionCell alloc] init];
yearCell.layer.shouldRasterize    = YES;
yearCell.layer.rasterizationScale = [UIScreen mainScreen].scale;
[yearCell setCurrentDate:newDate];

return yearCell;

}

我在viewDidLoad注册了自定义单元格的笔尖:

UINib * nib = [UINib nibWithNibName:@"AgendaYearCollectionCell" bundle:[NSBundle mainBundle]];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:myCellIdentifier];

MyCollectionViewCell是自定义(继承)UICollectionViewCell,其setCurrentDate方法可以:

-(void)setCurrentDate:(NSDate *)date
{

    if (calendar == nil)
        calendar = [[myCalendarView alloc] initWithDate:currentMonth];

     [self.contentView addSubview:calendar];
      calendar = nil;
   [self setNeedsDisplay];
}

问题是当我向视图添加/删除新单元格时,内存会线性增加。 我假设dequeueReusableCellWithReuseIdentifier做了我需要的事情:重用单元格来保持低内存使用率。 但这不会发生。例如,我的集合视图是一个日历:一个12个月的网格。因此,我总共需要12个细胞和12个细胞。 有一种方法可以更好地管理收藏品吗?

3 个答案:

答案 0 :(得分:2)

我在此处设置了重复小区标识enter image description here

修改 我认为这是您的问题,您每次都会在集合视图委托中添加日历,因此您只是重复使用MyCollectionCell,但calendar中的MyCollectionCell未被重复使用。这就是为什么您可以看到记忆印刷增长。因此,您应该使MyCalendarView更具可重用性,这样您就不必每次都分配它。

-(void)setCurrentDate:(NSDate *)date
{
    if (calendar == nil){
        calendar = [[myCalendarView alloc] initWithDate:currentMonth];
        [self.contentView addSubview:calendar];
       // calendar = nil;//here you dealloc calendar which make `if(calendar == nil)` run each time.
        [self setNeedsDisplay];
    }

}// each calendar in Collection Cell won't be create or refresh again.

答案 1 :(得分:0)

不要像cellForItemAtIndexPath中的UITabelView单元那样初始化CollectionViewCell。删除所有这些代码

//    if (yearCell ==  nil)
//        yearCell = [[AgendaYearCollectionCell alloc] init];
//    yearCell.layer.shouldRasterize    = YES;
//    yearCell.layer.rasterizationScale = [UIScreen mainScreen].scale;

因为您的单元格是Nib单元格,所以将这些设置带入MyCollectionCell.m中的awakeFromNib,就像这样

-(void)awakeFromNib{
[super awakeFromNib];
self.layer.shouldRasterize    = YES;
}

对于Nib单元格,registerNib就足够了,记得在Nib单元类中指定你的MyCollectionCell。

答案 2 :(得分:0)

使用Instruments分析应用的内存占用量。在XCode> Product> Profile并在Leaks上选择Instruments。跟踪高内存使用负责的调用是非常有用的。