什么时候应该使用__bridge vs. CFBridgingRelease / CFBridgingRetain? [英] when should you use __bridge vs. CFBridgingRelease/CFBridgingRetain?

查看:498
本文介绍了什么时候应该使用__bridge vs. CFBridgingRelease / CFBridgingRetain?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码使用__bridge来投射颜色的ID:

I have this code that uses "__bridge" to cast the ids of colors:

  CGColorRef tabColor = (5 == 5
                         ? [UIColor blueColor].CGColor
                         : [UIColor greenColor].CGColor);

  CGColorRef startColor = [UIColor whiteColor].CGColor;
  CGColorRef endColor   = tabColor;
  NSArray    *colors    = [NSArray arrayWithObjects:(__bridge id)startColor, (__bridge id)endColor, nil];

  CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

但会:

  NSArray    *colors    = [NSArray arrayWithObjects:(id)CFBridgingRelease(startColor), (id)CFBridgingRelease(endColor), nil];

  CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)CFBridgingRetain(colors), locations);

是更好的解决方案吗?

推荐答案

您不是拥有Core Foundation对象 startColor endColor 它们是
不是由其名称中具有创建或复制的函数返回的(比较创建规则在Core Foundation编程指南中
因为你不拥有对象,你不能传递所有

You don't "own" the Core Foundation objects startColor, endColor because they were not returned by a function that has "Create" or "Copy" in its name (compare "The Create Rule" in the "Memory Management Programming Guide for Core Foundation". And because you don't own the objects, you must not "transfer the ownership" to ARC with CFBridgingRelease(). So

[NSArray arrayWithObjects:(__bridge id)startColor, (__bridge id)endColor, nil];

CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

也是正确的,因为

CGGradientCreateWithColors(colorSpace, (CFArrayRef)CFBridgingRetain(colors), locations);

会将一个保留的数组传递给 CGGradientCreateWithColors code>。这将是一个记忆
泄漏,因为该函数不会释放颜色参数。

would pass a (+1) retained array to CGGradientCreateWithColors(). This would be a memory leak because that function does not release the colors argument.

这篇关于什么时候应该使用__bridge vs. CFBridgingRelease / CFBridgingRetain?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆