when should you use __bridge vs. CFBridgingRelease/CFBridgingRetain?

我怕爱的太早我们不能终老 提交于 2019-11-29 03:09:19

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];

is correct. And

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

is also correct because

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

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

With NSURL is the same problem

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
AudioServicesCreateSystemSoundID(CFBridgingRetain(soundURL), &soundEffect);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!