为什么使用 [UIColor colorWithRed:gred:blue:alpha] 会导致 EXC_BAD_ACCESS?
Why does using [UIColor colorWithRed:gred:blue:alpha] lead to EXC_BAD_ACCESS?
我已经创建了一个自定义的 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:]: message sent to deallocated instance 0x6000022d08c0
这是为什么?
当您使用 [UIColor blueColor]
时,您不会创建对象;你得到一个对它的引用,其他东西管理它的生命周期。
当您初始化一个新的 UIColor
对象时,您有责任确保它在使用时仍然有效。 "assign" 不会增加对象的引用计数; "strong" 确实如此。
我已经创建了一个自定义的 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:]: message sent to deallocated instance 0x6000022d08c0
这是为什么?
当您使用 [UIColor blueColor]
时,您不会创建对象;你得到一个对它的引用,其他东西管理它的生命周期。
当您初始化一个新的 UIColor
对象时,您有责任确保它在使用时仍然有效。 "assign" 不会增加对象的引用计数; "strong" 确实如此。