PHImageManager requestImageForAsset: 不起作用



我有一个组织文本笔记的应用程序。 我正在添加允许将照片添加到 (UITextView( 笔记的功能。 我添加了一个子类化的 UICollectionViewController 来向用户显示照片,他们可以从中选择要插入到笔记中的照片。

下面的 UICollectionView 委托方法旨在用照片填充集合视图。 我已经使用应用程序桌面图标作为"photoImage"的测试图像测试了这个视图控制器,一切正常。

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PHAsset *asset = (PHAsset *)[fetchResult objectAtIndex:indexPath.row];
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    options.synchronous = YES;
    NSLog(@" **** calling requestImageForAsset");
    __block UIImage *photoImage;
    __block dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    (void) [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(80.0,80.0) contentMode:PHImageContentModeAspectFit options:options
                   resultHandler:^(UIImage *img, NSDictionary *info)
                          {
                            NSError *e = [info objectForKey:PHImageErrorKey];
                            NSLog(@" **** error code (%ld), descr (%@)", (long)e.code, e.localizedDescription);
                            NSLog(@" **** img (%p)", img);
                            photoImage = img;
                            dispatch_semaphore_signal(sema);
                          }
          ];
    NSLog(@" **** returned from requestImageForAsset");
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    dispatch_release(sema);
    UIImageView *photoView = [[UIImageView alloc] initWithImage:photoImage];    <=== Thread 1: EXC_BAD_ACCESS (code=1, address=0x18)
    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Photo" forIndexPath:indexPath];
    [cell.contentView addSubview:photoView];
    return cell;

}

我的问题是来自requestImageForAsset:调用的结果处理程序。 显示 NSLog(( 输出的 Xcode 日志如下。

2014-12-13 13:18:18.918 iFilebox[23637:866056] **** 调用请求ImageForAsset 2014-12-13 13:18:18.939 iFilebox[23637:866056]错误代码 (0(, 描述 ((空(( <=== 未报告错误 2014-12-13 13:18:18.939 iFilebox[23637:866056] **** img (0x7fb4a97b6580( <=== 这是一个有效的内存地址吗?2014-12-13 13:18:19.940 iFilebox[23637:866056] **** 从请求返回ImageForAsset

在我想获取获取的图像并将其添加到集合视图单元格的位置,您可以看到问题:EXC_BAD_ACCESS。 我已经尝试了几种变体作为解决方法,但无济于事。 同样,如果我使用已知的静态图像代替从 resultHandler 返回的引用图像,则此代码工作正常。

有人可以解释为什么这段代码不应该工作,如果它应该=,为什么它不起作用? 有人对解决方法有任何想法吗?

即使您

设置了同步,我也想知道它是否到达了您绑定以实例化您的 UIImage photoView 的行,然后它实际上完成了获取您标记 img 的结果。尝试在requestImageForAsset的完成块中将img设置为cell.backgroundView,看看是否有效。

另外,也许这只是偏好,但在您执行任何操作之前,我会先实例化您的单元格。实际上,您可能希望对单元格进行子类化并在子类中设置图像。

最新更新