我已经创建了一个自定义的 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
对象时,您有责任确保它在使用时仍然有效。 “赋值”不会增加对象的引用计数; “强”确实如此。
关于ios - 为什么使用 [UIColor colorWithRed :gred:blue:alpha] lead to EXC_BAD_ACCESS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55431472/