Andrei Herford
Andrei Herford

Reputation: 18729

Why does using [UIColor colorWithRed:gred:blue:alpha] lead to EXC_BAD_ACCESS?

I have create a custom UIView subclass which should draw a simple dashed line. To define the color of the line I have added an inspectable property lineColor

// LineView.h
@interface LineView : UIView
@property (nonatomic,assign) IBInspectable UIColor *lineColor;
@end

// LineView.m
- (id)initWithFrame:(CGRect)frame{
    if((self = [super initWithFrame:frame])){
        [self setupView];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    if((self = [super initWithCoder:aDecoder])){
        [self setupView];
    }
    return self;
}


- (void)setupView {
    self.lineColor = [UIColor colorWithRed:0 green:0 blue:255.0 alpha:1.0];
    //self.lineColor = [UIColor blueColor];  <-- No Problem

    [self refreshLine];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self refreshLine];
}

- (void)refreshLine {    
    CGColorRef cgLineColor = self.lineColor.CGColor;  // <--CRASH
    ...
}

[UIDeviceRGBColor respondsToSelector:]: message sent to deallocated instance 0x6000022d08c0

Why is this?

Upvotes: 0

Views: 198

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

When you use [UIColor blueColor], you don't create the object; you get a reference to it and something else manages its life cycle.

When you init a new UIColor object, you're responsible for making sure it is still valid when used. "assign" doesn't increase the object's reference count; "strong" does.

Upvotes: 4

Related Questions