2

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?

YON
  • 1,607
  • 3
  • 18
  • 33
  • @matt Now that the contentTextView is a weak var, I think it should not cause the retain cycle no matter how the SmartTextView is implemented. Am I wrong? And I am sure the retain cycle is real. By the way, SmartTextView is just a subclass of UITextView I wrote to mimic the placeholder feature of UILabel and add autogrow feature, I can show the code if you needed. – YON Sep 14 '15 at 00:31

1 Answers1

2

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Maybe strong reference cycle is more properly? Now, the problem is that the when the viewcontroller is pushed and poped, it doesn't get deinit. – YON Sep 14 '15 at 00:53
  • I don't understand what you're saying. Your question was: why is the `unowned self` needed? I explained that. So keep the weak reference and keep the `unowned self`. And now you understand why. Right? – matt Sep 14 '15 at 00:55
  • OMG, I got what you are saying finally. Thanks! – YON Sep 14 '15 at 01:33