简体   繁体   中英

iPhone how to properly handle Core Foundation references with ARC?

I'm very new to the core foundation programming and would like to know what I'm thinking of doing is correct. I'm using ARC, and am not sure of how it handles non-object references. I need to save a reference to a sample buffer and use it later within the app. Is this possible, or will the sample buffer be deallocated prior to that?

Will using self.sampleBuffer = sampleBuffer_; cause memory leak? Do I need to add a manual call to release after this call?

@property (nonatomic)CMSampleBufferRef sampleBuffer;

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer_ fromConnection:(AVCaptureConnection *)connection
{
    //does this cause memory leak?
    self.sampleBuffer = sampleBuffer_;
}

It doesn't cause a memory leak. In fact, you're more likely to run into issues from the object being released out from under you, since properties have the assign attribute by default, which means they do not retain (read: own) the assigned object.

If you're holding onto the sample buffer long enough to need it to be a property, you should probably follow the docs and copy the samples to your own buffer instead of holding onto the object handed to your delegate:

If your application is causing samples to be dropped by retaining the provided CMSampleBuffer objects for too long, but it needs access to the sample data for a long period of time, consider copying the data into a new buffer and then releasing the sample buffer (if it was previously retained) so that the memory it references can be reused.

On the other hand, if you really want to keep a reference to the sample buffer, you can keep everything else as it is and call CFRetain on the object before you assign it to your property (making sure you CFRelease the object that was assigned before). This has equivalent semantics to the strong attribute for Foundation objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM