swiftdictionarystrong-references

Will a strong reference to a subview in a dictionary cause a reference cycle?


I have a view with variable subviews, the subviews are set up using a enum describing the type of this subview. My question is if the following would cause a strong reference cycle or if there is a better way to do this:

class ControlBar: UIView {

    var item = [ControlBarItemType : ControlBarItem]()

    func set(with types: [ControlBarItemType]) {

        for type in types {
            let newItem = ControlBarItem(frame: CGRect(), type: type)
            //constraints and stuff
            self.addSubview(newItem)
            item[type] = newItem

        }
    }
}

I can't declare the dictionary as weak. So the superview will have a reference to each ControlBarItem in the subview hierarchy and also with this dictionary, indexed by type. My reason for this is occasionally I need to change the state of the BarItem from the viewController that acts as the delegate for ControlBar.


Solution

  • You are NOT creating a strong reference cycle.

    Infact you have 2 strong reference from the ControlBar to each subview. This is not a problem.

    Instead, if you had a strong reference from ControlBar to the subviews AND a strong reference from the subviews to the ControlBar, you would have a strong reference cycle.

    enter image description here