iphone - 后台线程绘图中的错误访问

标签 iphone objective-c ios core-graphics cgimage

我想要完成的事情

  1. 在后台线程中绘制图像
  2. 转换 CGImageUIImage并将其添加到 UIImageView在主线程上。
  3. 淡入子类 UICollectionViewCell 上的 ImageView 从 alpha 值 0 到 1。
  4. 全部完成,这样滚动 UICollectionView 时就不会出现断断续续的情况。

问题

该行为起初表现正常,但很快就变得不可预测,通常很快就会导致 EXC_BAD_ACCESS。错误,发生在将 uiimage 转换为 cgimage 或反之亦然的过程中。

代码

    //setup for background drawing
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGContextRef context;
    context = CGBitmapContextCreate(NULL, 250, backgroundHeight - 112, 8, 250 * 4, colorSpaceRef, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
    CGColorSpaceRelease(colorSpaceRef);

    //Take the image I want drawn, convert to cgimage for background drawing
    CGImageRef  image = contentImage.CGImage;
    CGContextDrawImage(context, CGRectMake(0, 0, 250, backgroundHeight - 112), image);
    CGImageRelease(image);
    CGImageRef outputImage = CGBitmapContextCreateImage(context);
    imageRef = outputImage;

    [self performSelectorOnMainThread:@selector(addImageToView) withObject:nil waitUntilDone:YES];
    CGContextRelease(context);
    CGImageRelease(outputImage);

addImageToView 方法只是创建一个图像并添加到我的 UIImageView

UIImage * image = [UIImage imageWithCGImage:imageRef];
[photoView setImage:image];

这些方法在 cellForRowAtIndexPath 方法期间被调用,连同我的方法 fadeInImage

[UIView animateWithDuration:.6 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
    photoView.alpha = 1;
}completion:nil];

当我运行时,我收到 Bad Access 调用并崩溃。我猜它与主线程和后台线程在彼此之间传递图像有关。有任何想法吗?谢谢大家。

最佳答案

我认为,只要您没有使用 CGImageCreate 创建图像或使用 CGImageRetain,就不必使用 CGImageRelease(image);。一旦您停止使用它,它应该会自动释放。检查一下。

Apple documentation

关于iphone - 后台线程绘图中的错误访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13092669/

相关文章:

iphone - Xcode 4.0 验证错误 CFBundleVersion

ios - 将单元格数据(即 cell.textlabel.text 和 cell.imageView.image)传递给另一个 View Controller

ios - 在 AVPlayer 的请求中添加自定义 header 字段

ios - 裁剪AVCaptureSession预览

iphone - 在 plist 中存储图像

ios - 如何在 UITableview 的两行之间添加 UIView

ios - 如何清除迦太基缓存?

ios - 为每个 iPhone 型号提交单独的 IPA

iphone - 如何避免 iOS (MVC) 中同一模型对象的多个实例

ios - 如何在其他线程中打印主线程的回溯?