I am using SnapKit to handle my AutoLayout. I am wondering does this code cause a memory leak because I am capturing self in a closure?
writtenUpSwitch.snp.makeConstraints {
$0.trailing.equalToSuperview().inset(10)
$0.centerY.equalTo(writtenUpLabel.snp.centerY)
}
This line $0.centerY.equalTo(writtenUpLabel.snp.centerY) is accessing UILabel in a closure without using [weak self] In another of instance this will cause a memory Leak
The short answer is no, it doesn't.
The reason is mentioned in the comment under the original question – the closure is not
@escaping, it means it's not retained or captured by the closure to be dispatched somewhen later and it's dispatched in the same execution stack where it's allocated (likemap:,compactMap:and etc).When you're working with closures and captured values you should pay attention not only to
selfbeing retained by the closure. It's important to consider a potential retain cycles caused by any variable.Here's an example:
The problem here is not trivial, because we have no
selfinvolved in the closure. The cycle here is caused by retain chainobject->objectDependency->closure->object.