2010-06-27 19 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什么,所以如果你想拥有它的两倍乌尔上来的错™ - !但你已经有这个权利,所以我想大家都知道这一点。

相关问题