【问题标题】:UICollectionView Memory LeakUICollectionView 内存泄漏
【发布时间】:2014-07-14 22:09:23
【问题描述】:

您好,一旦在物理设备上测试了我的应用程序,下面的代码就会出现内存泄漏问题。我的问题是在滚动UiCollectioView 时出现的,但是这个视图控制器的加载速度也很慢。

所以我真正要做的是使用NSFileManger 直接从位于此路径 /var/mobile/Media/DCIM/100APPLE/ 的 iPhone DCIM 文件加载图像。获取这些图像后,我将它们放入一个数组中,并通过UICollectionView 用数组中的图像列表填充每个单元格,用它们创建一个画廊。例如单元格 1 = 图像 1,单元格 2 = 图像 2 等等。这可以正常工作,但是当滚动意外但有力地崩溃时,因此我假设这是内存泄漏问题。尤其是在模拟器上没有出现这个问题的时候。

这是我的代码:

    - (void)viewDidAppear:(BOOL)animated
    {
        // Do any additional setup after loading the view from its nib.
        path = @"/var/mobile/Media/DCIM/100APPLE/";
        Images = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil]mutableCopy];
    }

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    if ([[[Images objectAtIndex:indexPath.row]pathExtension] isEqualToString:@"JPG"])
    {
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];

    static NSString *identifier = @"Cell";

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@%@", path, [Images objectAtIndex:indexPath.row]]]]];


    UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 80, cell.bounds.size.width, 20)];
    v.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4f ];

    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 70, cell.bounds.size.width, 40)];
    title.tag = 200;
    title.text = [Images objectAtIndex:indexPath.row];
    title.textColor = [UIColor whiteColor];
    [cell.contentView addSubview:v];
    [cell.contentView addSubview:title];
    return cell;
    }
    else
        [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];

    static NSString *identifier = @"Cell";

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    return cell;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return Images.count;
}

提前谢谢...

PS: 我的应用程序正在构建为越狱手机的应用程序,所以请不要告诉我苹果不会接受我这样做的方式。

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    首先,您不应该假设您有内存泄漏,因为在使用 ARC 时这种情况并不常见;你应该使用仪器来测试。您有一个问题,您将视图 v 和标签标题添加到滚动时已经拥有它们的单元格,并且单元格被重用。这很可能是您的问题。就个人而言,我认为在 cellForItemAtIndexPath 中添加子视图是不好的形式,除非您将它们添加到某些单元格而不是基于 indexPath 的其他单元格。您应该创建一个自定义单元格,并在其 init 方法(或 IB 中)中添加子视图。另外,你只需要注册一次类,所以它不应该在 cellForItemAtIndexPath 中; viewDidLoad 是一个更好的放置位置。

    【讨论】:

    • 我删除了添加子视图的代码,但应用程序仍然崩溃?
    • @user2874682,你收到崩溃日志了吗?
    猜你喜欢
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2013-01-20
    相关资源
    最近更新 更多