objective-c - 将现有 CGColor 分配给 CGColor 属性适用于 iOS 模拟器,而不适用于 iOS 设备。为什么?

标签 objective-c ios ipad ios-simulator exc-bad-access

我知道如何解决我即将概述的问题,但是,我有点困惑为什么代码场景在 iOS 模拟器中有效,但在我的 iPad 上却无效。

我有一个方法可以检查各种属性,然后根据属性的状态设置 CALayer 的背景颜色。下面的代码和我的颜色分配方法类似:

//This will be the CALayer BGColor...
CGColor c = UIColor.blueColor.CGColor; //Blue is the default
switch (myState)
{
    case state_one:
        c = UIColor.greenColor.CGColor;
        //... more code ...
        break;
    case state_two:
        c = UIColor.redColor.CGColor;
        //... more code ...
        break;
    case state_three: //multiple cases are like the state_three case.
        //Other code, but I don't need to assign the color.  Blue works...
}

myCALayer.backgroundColor = c; //Oh-noes!!! Here we get the dreaded EXC_BAD_ACCESS on iPad
//...more code dealing with the layer.

上面的代码在模拟器中运行没有问题。但是,当我在 iPad 上运行该应用程序时,它在 backgroundColor 分配时崩溃。

我可以通过删除 CGColor 变量并直接在我的 switch/case 语句中分配背景颜色来解决这个问题,这就是我打算做的事情。

不过,我很好奇。为什么这会在一种环境中起作用,而在另一种环境中不起作用?

更新

一些事情。首先,值得一提的是,这是一个 ARC 项目,使用 Xcode 4.2,针对 iOS 5 设备。此外,我的颜色分配代码并不完全像它看起来的那样,因为我有一系列用于设置这些颜色的定义,因为它们在我的整个应用程序中都被引用。

这是一些 #define 语句的样子:

#define BLUE  [UIColor colorWithRed:8.0/255.0 green:80.0/255.0 blue:150.0/255.0 alpha:1.0].CGColor
#define GREEN (UIColor.blueColor.CGColor)
//...and there are about 6 other colors

我试图简化我的代码,因为编译器应该将我的引用替换为我的定义。尽管如此,还是值得一提以防万一。

最佳答案

由于 ARC,颜色在方法结束时过早释放。

我使用:CGColorRetain

CGColorRef whiteColor = CGColorRetain([UIColor colorWithRed:1.0 green:1.0
                                         blue:1.0 alpha:1.0].CGColor);

关于objective-c - 将现有 CGColor 分配给 CGColor 属性适用于 iOS 模拟器,而不适用于 iOS 设备。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9218664/

相关文章:

ios - 在事件监视器中释放更多非事件或文件缓存内存

ios - TabBar 覆盖了 TableViewController 的 TableView(需要 Swift 解决方案)

html - 从横向更改为纵向时强制 Ipad 缩小

iphone - 在 3/4 行之后,scrollToRowAtIndexPath 未滚动到正确的行

objective-c - 无法让 Cocoa 通知发挥作用

objective-c - 当 AfterdidCompleteWithError 调用时,如何使用 URLSession downloadTaskWithResumeData 再次开始下载..?

ios - viewWithTag 仅更新集合中的最后一个标签

iphone - 应用程序崩溃并发送到已释放实例的错误消息

ios - UISearchBarDelegate 和 textFieldShouldClear 替代方案

css - 在 ipad 中渲染 html 按钮