2010-06-27 23 views
0

見代碼,接口傳遞的UIColor的方法和應用程序崩潰

@interface ColorPreview : UIView { 
    UIColor *backgroundColor; 
} 
@property (retain) UIColor *backgroundColor; 

-(void) reDrawPreviewWith:(UIColor *)bgColor; 

@end 

實施

@implementation ColorPreview 

@synthesize backgroundColor; 
- (id)initWithFrame:(CGRect)frame { 

    if ((self = [super initWithFrame:frame])) { 
     // Initialization code 
     backgroundColor = [[UIColor alloc] init]; 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect { 
    ............ 
    //app crashes on this line 
    CGContextSetFillColorWithColor(context, [backgroundColor CGColor]); 

    NSLog(@"rect"); 
} 

-(void) reDrawPreviewWith:(UIColor *)bgColor 
{ 
    backgroundColor = bgColor; 
    [self setNeedsDisplay]; 
} 

- (void)dealloc { 
    [backgroundColor release]; 
    [super dealloc]; 
} 

@end 

叫我的方法是這樣

[preview reDrawPreviewWith:[UIColor colorWithRed:red green:green blue:blue alpha:1.0]]; 
+0

你能重命名'backgroundColor'到別的東西嗎?它與UIView自己的財產衝突。 – kennytm 2010-06-27 11:29:08

回答

3

加里幾乎右:
導致你崩潰的原因是你不是確實將您在reDrawPreviewWithColor:中獲得的顏色設置爲一個參數 - 事實上,您的reDraw...幾乎不會正常工作:它或者保持對它不擁有的對象的引用ie。 崩潰在自動釋放對象(你所看到的)或它泄漏

所以這裏有一個修復:

-(void)reDrawPreviewWithColor:(UIColor *)newColor 
{ 
    [self setBackgroundColor: newColor]; // or use the dot-syntax if you please ;-) 
    [self setNeedsDisplay]; 
} 

甚至更​​好廢料reDraw...共而是寫自己制定者backgroundColor因爲你無論如何都應該更新後的顏色重繪:

-(void)setBackgroundColor:(UIColor *)newColor 
{ 
    if (backgroundColor == newColor) 
     return; // if they are *identical*, there's nothing to do 

    [newColor retain]; 
    @synchronize(self) 
    { 
     [backgroundColor release]; 
     backgroundColor = newColor; 
     [self setNeedsDisplay]; 
    } 
} 

哦,而我們在這裏:
backgroundColor是一個原子屬性是否有很好的理由?您可能要考慮宣佈它作爲

@property (nonatomic, retain) UIColor *backgroundColor; 

這種方式,你可能放棄從我提出了二傳手的@synchronize指令。


一些很重要順便說一句:
加里建議在initWithFrame:self.backgroundColor = [[UIColor alloc] init]

不要!

你擁有你alloc什麼,所以如果你想擁有它的兩倍烏爾上來的錯™ - !但你已經有這個權利,所以我想大家都知道這一點。

相關問題