EXC_BAD_ACCESS使用IBInspectable [英] EXC_BAD_ACCESS Using IBInspectable
问题描述
我正在尝试使用 IBInspectable
为我的视图添加边框。
I am trying to use IBInspectable
to add borders to my views.
extension UIView {
private func getBorder(integer: Int) -> UIRectEdge {
if integer == 1 {
return .top
} else if integer == 2 {
return .left
} else if integer == 3 {
return .right
} else if integer == 4 {
return .bottom
}
return .all
}
@IBInspectable var border: Int? {
get {
return self.border
}
set (value) {
self.border = value
for v in addBorder(edges: self.getBorder(integer: self.border!)) {
self.addSubview(v)
}
}
}
@IBInspectable var borderColor: UIColor? {
get {
return self.borderColor
}
set (value) {
self.borderColor = value //EXC_BAD_ACCESS here
for v in addBorder(edges: self.getBorder(integer: self.border!), color: borderColor!) {
self.addSubview(v)
}
}
}
private func addBorder(edges: UIRectEdge, color: UIColor = UIColor.white, thickness: CGFloat = 1) -> [UIView] {
...
}
}
崩溃发生在 self.borderColor = value
行上(设置
borderColor
)。
The crash occurs on the line self.borderColor = value
(in the set
for the borderColor
).
调试日志中所说的全部是(lldb)
。崩溃本身说:
All it says in the debug log is (lldb)
. The crash itself says:
线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7fff53cc5fe8)
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7fff53cc5fe8)
这是我的故事板:
如何解决此问题?谢谢!
How can I fix this issue? Thanks!
推荐答案
你有一个无限递归,导致崩溃。基本上在 borderColor
的setter中你正在调用同一属性的setter,从而产生无限递归。
You have an infinite recursion there, that is causing the crash. Basically within the setter of borderColor
you're calling the setter for the same property, resulting the infinite recursion.
这是因为类扩展不允许存储属性,因此Swift不会为您的属性生成反向存储,而是将其视为计算属性,并在您尝试设置属性时调用setter。
This happens because class extensions are not allowed to have stored properties, so Swift doesn't generate a backstore for your property, instead it treats it like a computed property, and calls the setter whenever you try to set the property.
目前我可以想到两个解决方案,这将解决您的问题:
There are two solutions that I can think of at this time, that will solve your problem:
- Subclass UIView,在那里添加两个属性,更新IB中的类以匹配新类的名称。
- 在
UIView中使用关联对象
访问器(objc_setAssociatedObject()
/objc_getAssociatedObject()
)而不是直接的iVar引用。你不需要子类化和更新你的xib,但是这个解决方案比第一个解决方案有点麻烦。
- Subclass UIView, add the two properties there, update the class in IB to match the name of your new class.
- Use associated objects in your
UIView
accessors (objc_setAssociatedObject()
/objc_getAssociatedObject()
) instead of direct iVar reference. You will not need to subclass and to update your xibs, however this solution is a little bit messier than the first one.
这篇关于EXC_BAD_ACCESS使用IBInspectable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!