简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM