objective-c - 将自动释放的 CGColor 返回到 ARC 的转换方法

标签 objective-c xcode cocoa automatic-ref-counting core-foundation

我正在将我的项目转换为使用 ARC。我在 NSColor 上有一个类别,其方法返回自动发布的 CGColor 表示:

@implementation NSColor (MyCategory)

- (CGColorRef)CGColor
{
    NSColor *colorRGB = [self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
    CGFloat components[4];
    [colorRGB getRed:&components[0]
               green:&components[1]
                blue:&components[2]
               alpha:&components[3]];
    CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGColorRef theColor = CGColorCreate(space, components);
    CGColorSpaceRelease(space);
    return (CGColorRef)[(id)theColor autorelease];
}

@end

使用 ARC 执行此操作的正确方法是什么?我不想返回保留的 CGColor。

XCode 中的 ARC 转换器建议使用
return (CGColorRef)[(__bridge id)theColor autorelease];

但这会导致以下错误消息:

[rewriter] it is not safe to cast to 'CGColorRef' the result of 'autorelease' message; a __bridge cast may result in a pointer to a destroyed object and a __bridge_retained may leak the object

最佳答案

CGColor是一个核心基础对象。您不应该尝试使用 autorelease用它。相反,您应该重命名您的方法 copyCGColor并返回一个保留的对象。

自动释放是一个 Objective-C 的概念。它在核心基金会级别不存在。

CGColor不是免费桥接到任何 Objective-C 类,尝试自动释放它是非常奇怪的(即使这可能有效)。

几年后更新

现在在 CoreFoundation 级别有 CFAutorelease()(自 Mavericks 和 iOS 7 开始可用)。

关于objective-c - 将自动释放的 CGColor 返回到 ARC 的转换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636369/

相关文章:

objective-c - 自迁移以来导航栏和表格 View 之间的黑条

ios - 应用程序在 isHidden 属性上崩溃

ios - Swift 3 numberOfRows TableView 函数错误

ios - EWS - 如何传递自动发现凭据 - ios、cocoa

cocoa - 如何读取 NSAutoresizingMaskLayoutConstraint 的日志输出?

ios - 根据架构在 Objective-C 中进行条件导入

ios - UIDeviceOrientationDidChangeNotification 返回错误的方向

ios - 在 iOS/Xcode 中将单个 View 转换为选项卡式应用程序

iOS:xcode 5,将项目从 xctest 迁移到 senTestingKit

objective-c - 设置不透明 :NO vs setBackgroundColor:[NSColor clearColor]