EXC_BAD_ACCESS Using IBInspectable

那年仲夏 提交于 2019-12-20 05:50:18

问题


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] {
        ...
    }
}

The crash occurs on the line self.borderColor = value (in the set for the borderColor).

All it says in the debug log is (lldb). The crash itself says:

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7fff53cc5fe8)

Here is my storyboard:

How can I fix this issue? Thanks!


回答1:


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.

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:

  1. Subclass UIView, add the two properties there, update the class in IB to match the name of your new class.
  2. 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.


来源:https://stackoverflow.com/questions/39197048/exc-bad-access-using-ibinspectable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!