繁体   English   中英

在iOS中从UIColor获取CGColor时发生异常

[英]Exception when getting CGColor from UIColor in iOS

我正在尝试为我的视图创建自定义按钮。 一切正常,除了渲染时,我的颜色被抛出异常。 我的课有2个颜色属性:

@property (nonatomic, retain) UIColor* defaultBackground;
@property (nonatomic, retain) UIColor* clickedBackground;

一种表示默认的渲染颜色,另一种表示用户单击时的颜色。 在我的initWithFrame方法中,我初始化了颜色:

defaultBackground = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
clickedBackground = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

一切都很好,直到我到达在获取CGColor时抛出异常的渲染为止:

if((self.state & UIControlStateHighlighted) == 0)
    {
        CGContextSaveGState(context);
        CGContextSetFillColorWithColor(context, defaultBackground.CGColor); //Crashes on this line
        ...

这是我得到的例外:

2012-04-13 10:19:51.005 -[__NSMallocBlock__ CGColor]: unrecognized selector sent to instance 0x7d94d20
2012-04-13 10:19:51.072 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSMallocBlock__ CGColor]: unrecognized selector sent to instance 0x7d94d20'

任何想法将不胜感激。

更改initWithFrame:的两行:

self.defaultBackground = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
self.clickedBackground = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

问题在于,将自动释放的UIColor对象直接分配给ivar会导致指向释放对象的指针悬空。 一种替代方法是:

defaultBackground = [[UIColor alloc] initWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
clickedBackground = [[UIColor alloc] initWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

您需要做-

self.defaultBackground = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
self.clickedBackground = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

...否则,他们将不会被保留。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM