EXC_BAD_ACCESS 在 dispatch_async 中传递参数时 objective-C

EXC_BAD_ACCESS when passing a parameter in dispatch_async in objective-C

我将变量传递给另一个方法。访问此 属性 应用程序时崩溃并出现 EXC_BAD_ACCESS 错误。

   in class1: 
  CVPixelBufferRef pixelBuffer;
  @implementation class1
     - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
        pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        dispatch_async( dispatch_get_main_queue(), ^{
           predictions = [dTFG runX:pixelBuffer orientation: UIDeviceOrientationPortrait CardRect: _vwRect];

       }
     }
   } 

    in class2:
    - (NSArray*) runX:(CVPixelBufferRef) pixelBuffer orientation: (UIDeviceOrientation) orientation CardRect:(CGRect) CardRect {
       CFRetain(pixelBuffer);  // Error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x800000060)
    }

Thread 1: EXC_BAD_ACCESS (code=1, address=0x800000060)

当我评论 dispatch_async 时,崩溃没有发生。

根据另一个答案,这个错误是(可能)因为释放了对象。但是为什么在这种情况下发布了而没有dispatch_async,却没有发布。

CMSampleBufferGetImageBuffer()返回的CVImageBufferRef不是一个对象,只是一个C结构体,所以不参与引用计数。如果您要将其传递到异步运行的块中,则需要确保该数据保持有效。请注意,文档明确告诉您:

The caller does not own the returned buffer, and must retain it explicitly if the caller needs to maintain a reference to it.

我没有深入研究它,但考虑到数据类型,这可能意味着您需要在 pixelBuffer 上调用 CVBufferRetain()(然后 CVBufferRelease() 当您重新完成它)。