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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With