ios - 滚动 UICollectionView 使用大量内存导致崩溃

标签 ios memory-leaks uicollectionview uilabel uicollectionviewcell

我正在开发表情符号键盘。这是我的方法:

  • 我决定使用 UICollectionView。我在代码中做所有事情,不打算使用 Xib 文件。
  • 我创建了 UICollectionViewCell 的子类。这将包含一个显示表情符号的标签。这就是我在其 initWithFrame 中所做的

    - (instancetype)initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
        if (self) {
            if (_label == nil) {
            _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    
            _label.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                       UIViewAutoresizingFlexibleHeight);
    
            _label.textAlignment = NSTextAlignmentCenter;
            [_label setNumberOfLines:1];
            self.contentView.layer.cornerRadius = 6.0;
    
            [self.contentView addSubview:_label];
            }
        }
    
        return self;
    }
    
  • 在 UICollectionView 数据源对象中,我读取了一个包含 NSDictionary 的 plist 文件,其中 NSString 作为键,NSArrays 作为值。在每个 NSArray 中,可以找到我要显示的表情符号。然后我将字典存储在一个属性中。这是代码:

    @property (nonatomic, strong) NSDictionary *emojis;
    
    - (NSDictionary *)emojis {
         if (!_emojis) {
              NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"EmojisList"
                                                          ofType:@"plist"];
             _emojis = [NSDictionary dictionaryWithContentsOfFile:plistPath];
        }
        return _emojis;
    }
    
  • 在下面的方法中,我尝试填充单元格:

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
            NSString *cellIdentifier = @"Cell";
    
            EmojiCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
            cell.label.font = [UIFont systemFontOfSize:self.isiPad ? 47 : 33];
    
            NSArray *dataArray = [self.emojis objectForKey:self.categoryNames[indexPath.section]];
            cell.label.text = dataArray[indexPath.row];
    
            return cell;
    }
    

我遇到的问题是,滚动时内存使用量会增加。这会导致在真实设备上崩溃。

请帮帮我。我测试了许多不同的方法来解决这个问题,但都没有成功。

这是仪器的屏幕截图。我真的不知道那些是关于什么的。

Memory Usage increases when I scroll

最佳答案

字体大小的作用。

“Apple Color Emoji”字体根据字体大小将表情符号字符替换为不同大小的 PNG 图像。较大的图像很快就会用完 40MB 的内存限制。

在我的例子中,我尝试使用 16 的字体大小并使用 1.5 比例变换使其足够大。结果看起来不太好,但至少它有效...

关于ios - 滚动 UICollectionView 使用大量内存导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655552/

相关文章:

ios - CollectionView 单元格上的 UISwipeGestureRecognizer 无法正常工作

c - 我是否有可能知道我是否已在 C 中正确清理?

ios - 初始化时的用户单例和 nsuserdefault

ios - 尝试使用 SnapKit 在自定义 UITableViewCell 中布局 UILabels 时收到警告

objective-c - 如何减小使用相机拍摄的快照的文件大小?

javascript - 如何修复这个window.open IE内存泄漏?

c++ - 未对 C++ STL 容器对象调用clear() 时发生内存泄漏

ios - 如何在 UICollectionViewCell 中显示 UITableView

ios - 以编程方式用数组中的数据填充 UICollectionView 中的 UICollectionViewCells

ios - 在 Swift 中以编程方式在 UITableViewCell 中创建 UICollectionView