gpt4 book ai didi

ios - 自定义 UICollectionViewCell 增加内存分配

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:47 25 4
gpt4 key购买 nike

完成我的应用程序后,我意识到内存分配非常巨大。我想我已经将问题隔离到一个使用 UICollectionView 的 View 。 Collection View 具有自定义 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中注册了自定义单元格的nib:

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];
}

问题是内存随着我向 View 中添加/删除新单元格而线性增加。我假设 dequeueReusableCellWithReuseIdentifier 做了我需要的事情:重用单元格以保持低内存使用率。但这不会发生。例如,我的 Collection View 是一个日历:12 个月的网格。因此,我总是需要 12 个且只需要 12 个单元格。有更好的方法来管理馆藏吗?

最佳答案

我在这里设置了我的重用单元标识符 enter image description here

编辑:我认为这是你的问题,你每次都在 Collection View 委托(delegate)中添加日历,所以你只是重用了你的 MyCollectionCell 但你在 MyCollectionCell 中的 calendar 是未重复使用。这就是为什么您可以看到内存打印增长的原因。所以,您应该使 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.

关于ios - 自定义 UICollectionViewCell 增加内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20719503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com