CGContextRef – EXC_BAD_ACCESS错误

我是UIView的子类,并使用它的实例来设置我的UITableViewCell backgroundView和selectedBackedView属性。 我在我的UIView子类的drawRect方法中收到一个EXC_BAD_ACCESS错误。

if(nil == cell){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; cell.backgroundView = [[CCViewBackground alloc]init]; cell.selectedBackgroundView = [[CCViewBackground alloc]init]; } 

UIView子类CCBackgroundView -drawRect:

 - (void)drawRect:(CGRect)rect { // Drawing code CGContextRef context = UIGraphicsGetCurrentContext(); CGColorRef redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0].CGColor; CGContextSetFillColorWithColor(context, redColor); //Receiving EXC_BAD_ACCESS here CGContextFillRect(context, self.bounds); } 

我假设你正在使用ARC。 如果是这样,您遇到了一个众所周知的问题,即CGColorRef的发布时间比您预期的要早。 本文详细解释了该问题并提供了几种解决方案。