Is using SnapKit causing memory leaks

111 Views Asked by At

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

1

There are 1 best solutions below

0
Aleksandr Larionov On

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 (like map:, compactMap: and etc).

When you're working with closures and captured values you should pay attention not only to self being retained by the closure. It's important to consider a potential retain cycles caused by any variable.

Here's an example:

let objectDependency = SomeObjectDependency()
let object = SomeObject(dependency: objectDependency) /// dependency is retained here

objectDependency.someAsyncFunc(withCompletion block: @escaping () -> ()) { in
   object.doSomeSomething() /// here we have a retain cycle!
}

The problem here is not trivial, because we have no self involved in the closure. The cycle here is caused by retain chain object -> objectDependency -> closure -> object.