Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

ios - when should you use __bridge vs. CFBridgingRelease/CFBridgingRetain?

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

but would:

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

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

be a better solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...