When compiling this OSX App in XCode 10 beta 2 (Swift 4.2), I get a warning that did not show in XCode 9.4 each time I create an NSConstraint programmatically
Instance will be immediately deallocated because property 'myConstraint' is 'weak'
fileprivate weak var myConstraint : NSLayoutConstraint!
myConstraint = NSLayoutConstraint(item: aButton, attribute: .top, relatedBy: .equal, toItem: aView, attribute: .bottom, multiplier: 1.0, constant: 30)
However, there is no such warning for IBOutlet
@IBOutlet fileprivate weak var anotherConstraint : NSLayoutConstraint!
Is it a just a new warning for an error that existed before ? Or did something change in NSConstraint ?
Should I treat IBOutlet and programmatically created differently with respect to weak ?
It's different with IBOutlet.
In that case, the constraint is loaded from a NIB file. Your view controller or window controller holds a strong reference to the array of top level objects from the NIB. Those top level objects in turn hold strong child references to their subordinate objects, and so on all the way down. That means the entire object graph loaded from the NIB is kept alive by the controller, and it does not matter whether your IBOutlet is strong or weak.
This is described (in excruciating detail) in this document:
It might not be absolutely up to date, but I'm not aware of anything important that's changed in the last 2 years.
Your weak variable is a different case. As soon as the assignment is complete, there is nothing keeping the constraint alive, so it will be deallocated. If you need to keep it alive long enough to (say) add to a view, use a local variable to hold the result of creating it, assign that to your weak variable, and then add it to the view.