Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does setting `constraint.isActive = false` deallocate the constraint?

Say I want to remove a constraint, traditionally I would do:

view.removeConstraint(constraint)

However, there is now the new isActive methods for installing/uninstalling constraints.

If I do the following:

constraint.isActive = false

Will it remove it from memory correctly?

like image 673
Senseful Avatar asked Sep 13 '17 21:09

Senseful


1 Answers

Yes,

constraint.isActive = false

is doing the same thing as:

viewThatOwnsConstraint.removeConstraint(constraint)

So if the only thing holding on to the constraint was the view, then this will correctly remove it from memory.


Here's the proof:

let view = UIView()

weak var weakView: UIView? = nil
autoreleasepool {
  weakView = UIView()
}
assert(weakView == nil)

// Traditional way of removing constraints ensures that the constraint is deallocated

weak var weakConstraint: NSLayoutConstraint? = nil
autoreleasepool {
  weakConstraint = view.widthAnchor.constraint(equalToConstant: 10)
}
assert(weakConstraint == nil) // nothing is holding on to the constraint

autoreleasepool {
  weakConstraint = view.widthAnchor.constraint(equalToConstant: 10)
  view.addConstraint(weakConstraint!)
}
assert(weakConstraint != nil)

autoreleasepool {
  view.removeConstraint(weakConstraint!)
}
assert(weakConstraint == nil)

// New way of removing constraints:

assert(weakConstraint == nil)

autoreleasepool {
  weakConstraint = view.widthAnchor.constraint(equalToConstant: 10)
  weakConstraint!.isActive = true
}
assert(weakConstraint != nil)

autoreleasepool {
  weakConstraint!.isActive = false
}
assert(weakConstraint == nil)
like image 106
Senseful Avatar answered Nov 13 '22 03:11

Senseful