【问题标题】:Why does using [UIColor colorWithRed:gred:blue:alpha] lead to EXC_BAD_ACCESS?为什么使用 [UIColor colorWithRed:gred:blue:alpha] 会导致 EXC_BAD_ACCESS?
【发布时间】:2019-08-21 05:21:55
【问题描述】:

我创建了一个自定义的UIView 子类,它应该画一条简单的虚线。为了定义线条的颜色,我添加了一个可检查的属性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
    ...
}
  • 如果在 Interface Builder 中分配了颜色,一切正常
  • 如果指定了默认颜色,如 [UIColor blueColor],则一切正常
  • 如果像[UIColor colorWithRed:0 green:0 blue:255.0 alpha:1.0] 这样的自定义颜色,应用程序崩溃并显示EXC_BAD_ACCESS

[UIDeviceRGBColor respondsToSelector:]:消息发送到已释放实例 0x6000022d08c0

这是为什么?

【问题讨论】:

  • 您是否尝试使用 strong 更改分配? 255.0 至 255.0 / 255.0
  • 谢谢,这确实解决了问题。但是为什么使用 [UIColor blueColor] 的 assign 可以,而 colorWithRed:green:blue:alpha 失败?

标签: ios objective-c uiview uicolor


【解决方案1】:

当您使用[UIColor blueColor] 时,您不会创建对象;您会获得对它的引用,而其他东西会管理它的生命周期。

当您初始化一个新的UIColor 对象时,您有责任确保它在使用时仍然有效。 "assign" 不会增加对象的引用计数; “强”可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多