簡體   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