Search code examples
objective-cswiftautomatic-ref-countingcore-foundationcore-video

CVMetalTextureGetTexture ownerhsip?


I'm trying to figure out how the ownership works with the function CVMetalTextureGetTexture:

CVMetalTextureRef textureRef;
// ... textureRef is created
id<MTLTexture> texture = CVMetalTextureGetTexture(_textureRef);
CVBufferRelease(textureRef); // Releasing the existing texture
// Is texture still valid here?

Is texture still valid after releasing textureRef? If not, can I somehow transfer ownership from textureRef to texture (ARC), so I don't have to call CVBufferRelease later when texture is released?

The same question for swift:

var texture: MTLTexture
do {
  var textureRef: CVMetalTexture
  // ... textureRef is created
  texture = CVMetalTextureGetTexture(textureRef)!
  // end of scope, textureRef is released
}
// Is texture still valid here?

Solution

  • This is an excellent question since this kind of breaks the Create Rule, but it seems like this method indeed retains the underlying object. I guess this rule doesn't apply for Core Foundation -> ARC methods...

    You can see in this Apple Demo that they do release the ref after converting it to an id<MTLTexture>. They do it in the more implicit Swifty version so it's easily missed.