简体   繁体   English

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

[英]Exception when getting CGColor from UIColor in iOS

I am trying to create custom buttons for my views. 我正在尝试为我的视图创建自定义按钮。 Everything works well except when rendering I am getting an exception being thrown regarding my colors. 一切正常,除了渲染时,我的颜色被抛出异常。 My class has 2 color properties: 我的课有2个颜色属性:

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

One to represent the default rendering color and the other for when the user has it clicked. 一种表示默认的渲染颜色,另一种表示用户单击时的颜色。 Inside my initWithFrame method I initialize the colors: 在我的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];

This is all well and good until I get to the rendering where it throws an exception when getting the CGColor: 一切都很好,直到我到达在获取CGColor时抛出异常的渲染为止:

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

Here is the exception that I am getting: 这是我得到的例外:

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'

Any ideas would be greatly appreciated. 任何想法将不胜感激。

Change the two lines in your initWithFrame: as follows: 更改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];

The problem is that assigning an autoreleased UIColor object directly to an ivar results in a dangling pointer to a released object. 问题在于,将自动释放的UIColor对象直接分配给ivar会导致指向释放对象的指针悬空。 An alternative is: 一种替代方法是:

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

You need to do - 您需要做-

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

...otherwise they're not being retained. ...否则,他们将不会被保留。

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

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