Search code examples
iosretain-cycle

iOS - Weak var can still cause retain cycle?


Here is my real code:

@IBOutlet weak var contentTextView: SmartTextView! {
    didSet {
        self.contentTextView.onDidBeginEditing = {
            $0.layer.borderColor = Util.green.CGColor
        }
        self.contentTextView.onDidEndEditing = {
            $0.layer.borderColor = Util.gray.CGColor
        }
        self.contentTextView.layer.borderWidth = 1 / Util.screenScale
        self.contentTextView.layer.borderColor = Util.gray.CGColor
        self.contentTextView.minHeight = 148
        self.contentTextView.maxHeight = 148
        self.contentTextView.onChange = { [unowned self] text in
            var content = text.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "\n\t"))
            self.contentLenthLabel.text = "\(self.MAX_CONTENT - count(content))"
        }
    }
}

If I remove [unowned self] statement, I can see a retain cycle problem in Instruments.

Is the KVO or something else make a weak var can still cause retain cycle?


Solution

  • The weak reference is a red herring; it has nothing to do with the story here. Without the [unowned self], you are retaining this view and this view is retaining you. That's a retain cycle:

    • UIViewController retains its view

    • View retains its subviews; one of those subviews is the SmartTextView

    • SmartTextView retains the onChange function

    • Function retains self (the UIViewController) unless you say unowned self.