objective-c - DCRoundSwitch 在使用 ARC 时给出 EXC_BAD_ACCESS

标签 objective-c cocoa-touch ios5 exc-bad-access automatic-ref-counting

我正在使用 DCRoundSwitch对于我基本上需要一个 UISwitch 的项目,我可以在其中编辑其标签内容。

因为我使用的是 ARC,所以我重构了 DCRoundSwitch 代码,使其在 xcode 中与 ARC 兼容。

在模拟器中编译和运行时没有任何问题。

但是,当在设备上运行时,它在 DCRoundSwitchKnobLayer.m 的第 57 行附近给了我 EXC_BAD_ACCESS

有一个bug report在 GitHub 上,但尚未找到解决方案。

这是给出 EXC_BAD_ACCESS 的代码:

CGGradientRef CreateGradientRefWithColors(CGColorSpaceRef colorSpace, CGColorRef startColor, CGColorRef endColor)
{
    CGFloat colorStops[2] = {0.0, 1.0};
    CGColorRef colors[] = {startColor, endColor};

    //THIS LINE BREAKS THE PROGRAM
    CFArrayRef colorsArray = CFArrayCreate(NULL, (const void**)colors, sizeof(colors) / sizeof(CGColorRef), &kCFTypeArrayCallBacks); 

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, colorsArray, colorStops);
    CFRelease(colorsArray);
    return gradient;
}

如有任何线索,我们将不胜感激。

编辑:这是来自 xcode 的局部变量:

enter image description here

最佳答案

我遇到了同样的问题,我真的很想将代码转换为 ARC。 发生崩溃是因为调用 CreateGradientRefWithColors 时已经释放了 startColor 和 endColor。

这是我的修复:

- (void)drawInContext:(CGContextRef)context
{
    UIColor *startColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
    UIColor *endColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

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

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

这篇文章有助于找到解决方案:http://www.bobmccune.com/2012/02/28/a-funny-thing-happened-on-the-way-to-the-arc/

关于objective-c - DCRoundSwitch 在使用 ARC 时给出 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8457466/

相关文章:

iphone - 来自 AppDelegate.m 的当前 ViewController 类名的 NSLog

ios5 - 如何在 ios5 中自定义 UIBarButtonItem

iphone - 使 UICollectionView 中的 insertItemsAtIndexPath 不设置动画

objective-c - 使用任何东西在 Objective-C 中加密/在 Ruby 中解密

ios - 当我使用 NSPredicate 为我的 UITableView 过滤我的数组时,应用程序崩溃

cocoa - 停止 NSRunLoop

ios - 向左滑动时如何处理 UITableViewCell 删除按钮动画?

ios - 在 Swift 中读取 NSNotification userInfo

iphone - 在iPhone中绘图后如何将两个 ImageView 保存在一个 ImageView 中

ios - 生成唯一文件名的 MPMediaItem