Search code examples
swiftweak-referencescustom-viewretain-cycle

iOS datasource and outlet references


I viewed some Stanford iOS development classes on Youtube, and I found something that's not clear to me. In the lecture the professor explains how to create custom views and custom data source classes, and the code is the following:

FaceView.swift

protocol FaceViewDataSource: class {
    // some stuff here
}

class FaceView: UIView {

    // some uninteresting properties here

    weak var dataSource: FaceViewDataSource?

    // other stuff here
}


HappinessViewController.swift

class HappinessViewController: UIViewController, FaceViewDataSource {

    @IBOutlet weak var faceView: FaceView!

    // other stuff here
}


The professor said that the dataSource property must be declared as a weak property to avoid retain cycles between the view and the view controller.

My question is: why do we have a retain cycle if we declare the dataSource property as strong? Since the outlet property is weak, isn't the retain cycle already avoided?


Solution

  • No, it's not. See the description below.

    • View controller keeps strong reference to his view.
    • View controller's view (not view controller) keeps strong reference to faceView.
    • FaceView keeps strong reference to View controller.