0

Say, I'm building a custom UISegmentedControl by laying out several buttons and describing their states. I am attaching TouchUpInside listeners to them in order to change their appearance accordingly, when selected. The problem is that I don't know where to remove these listeners in order to avoid a memory leak. UIView and UIControl don't have ViewDidDisappear like UIViewController which I'm using to remove listeners when it becomes invisible.

Where should I remove these listeners?

nicks
  • 2,161
  • 8
  • 49
  • 101

2 Answers2

1

I would suggest looking at when the following are called, and see if they suit your needs for UIView:

didAddSubview:, willRemoveSubview: Implement these methods as needed to track the additions and removals of subviews. willMoveToSuperview:, didMoveToSuperview Implement these methods as needed to track the movement of the current view in your view hierarchy.

willMoveToWindow:, didMoveToWindow Implement these methods as needed to track the movement of your view to a different window.

(Above taken from this SO post: SO Reply)

This would allow you to follow what the 'superview' is doing with the view, and when it's being dismissed you should be able to run your clean up code.

Community
  • 1
  • 1
JoeTomks
  • 3,243
  • 1
  • 18
  • 42
0

You don't need to remove your "listeners". UIControl doesn't hold strong references to targets - from the documentation for addTarget(_: action: for:):

The control does not retain the object in the target parameter. It is your responsibility to maintain a strong reference to the target object while it is attached to a control.

jrturton
  • 118,105
  • 32
  • 252
  • 268