views:

532

answers:

1

I am confused why my app is crashing with this error.

I have implemented the displayLayer method (for rendering CALayer). The first time this method runs things work fine. But subsequent calls to this is when the error occurs.

The error seems to occur when the self.bgColor is being set to the context fill color. INTERESTINGLY... if I create the bgColor right before that line, things work. But as it stands, the bgColor is being created upon initialization of this class (the container of the displayLayer method).

-(void)displayLayer:(CALayer *)caLayer
{
  UIGraphicsBeginImageContext(caLayer.frame.size);
  CGContextRef context = UIGraphicsGetCurrentContext();    
  CGContextSetFillColorWithColor(context, self.bgColor);
  CGContextFillRect(context, CGRectMake(0, 0, 320, 25)); 
  [self drawText:context];
  // get image buffer
  UIImage *imageBuffer = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  // set layer contents to image buffer
  caLayer.contents = (id)[imageBuffer CGImage];
}
A: 

I haven't done much iPhone programming yet, and never used a CGColor instance variable, so what I would do is this:

@interface {
    ....
    UIColor *bgColor;
    ....
}
@property (nonatomic, retain) UIColor *bgColor;
...
@end

@implementation
@synthesize bgColor;
- (id)init {
    ...
    self.bgColor = [UIColor blackColor];
    ...
}
-(void)displayLayer:(CALayer *)caLayer {
    ...
    CGContextSetFillColorWithColor(context, self.bgColor.CGColor);
    ...
}
...
@end

[UIColor blackColor] returns an autoreleased object, and you assigned it to your instance variable without retaining it.

Using self.bgColor instead of just bgColor in init and having set up the property to retain its value will make sure that the color is retained and can be used in displayLayer later on.

As I mentioned I don't have any experience with using CGColors directly, that's why I'm using a UIColor in the above code. Please adjust as needed.

Thomas Müller
Hmmm....the whole thing between self and non using self is apparantly not quite solidified in my mind. But what you just said makes sense to me. I've already adjusted to use UIColor* instead of CGColor.Thank you for your help.
AlvinfromDiaspar
synthesize bcColor will generate two methods: -(UIColor *)bgColor and -(void)setBgColor:(UIColor *)aColor;. These methods handle retaining and releasing the objects. Using self.bgColor = xxx is equivalent to calling [self setBgColor:xxx] and using xxx = self.bgColor is equivalent to calling xxx=[self bgColor], so all the retaining and releasing is taken care of. If you directly read or modify the instance variable (without self), you'd have to do the retaining and releasing yourself.
Thomas Müller