How do I destroy a layout constraint object?

It doesn't seem like an NSLayoutContraint object is destroyed by ARC when there is no longer a reference for it. In that case, how do I destroy one when I no longer need it?

Replies

How do you know the constraint is not cleared ? In which circumstances ? Are you sure the instance in which the constraint is defined is effectively deinit ?


You can use

NSLayoutConstraint.deactivateConstraints

to deactivate the constraint.


But in general, this constraint is declared in a class hence created with the instance. When the instance is deinit, the constraint is cleared as well.

"How do you know the constraint is not cleared ? In which circumstances ?"


I was actually talking about how a layout constraint is created like in the follwoing code:


        NSLayoutConstraint(item: viewAlarms, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leadingMargin, multiplier: 1, constant: 0).isActive = true


In the code above, the layout constraint is not assigned to a variable, but is active. Normally an object is deinitialized when the variable that references it goes out of scope and ARC automatically releases it. But in this case there is no variable referencing the layout contraint object.


"Are you sure the instance in which the constraint is defined is effectively deinit ?"


No, I'm not sure at all. That's what I'm trying to find out how to do. How do I deinitialze the layout constraint instance and free up the memory space it was using?

References to constraints are kept in the "constraints" property of the UIView to which the constraints were applied (first common ancestor), as far as I know. They should be released when the view is removed from the view hierarchy.


I think if you wanted to destroy one that you had created in code, you'd have to keep a reference to it and specifically remove it from the parent before setting your reference to nil.

Here is an example :


I create the constraint in code, assigining to a var:

    private weak var aConstraint    : NSLayoutConstraint!

When needed, I initialize

    aConstraint = NSLayoutConstraint(item: anObject1, attribute: .Leading, relatedBy: .Equal, toItem: anObject2, attribute: .Trailing, multiplier: 1.0, constant: 5) 
    aConstraint!.identifier = "#01"


But anyway, when object instance is deinit, all var that were created inside, explicitely or not are freed.

There should be no need to free (delete) the constraint when the object still exist.