Strong Reference Cycle


(Grzegorz Leszek) #1

Hello Swift Community,

According to the Swift Programming Language Book:

“A strong reference cycle can also occur if you assign a closure to a
property of a class instance, and the body of that closure captures
the instance.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/pl/jEUH0.l

Does it mean that example below is valid? ( no need to use capture list ):

import Swift

class A {}

class Foo {
    var object = A()
    func bar() {
        Bar().start {
            print(self.object)
        }
    }
}

class Bar {
    func start(completion: () -> ()) {
        completion()
    }
}

As far as I understand, Leak will occur when class Bar stores
completion in the property. But are there any other edge cases ?

Regars,
Greg Leszek


(Zhao Xin) #2

Bar() will be released as soon as start(:)'s finishes execution. As there
is no strong reference to Bar() and the closure runs inside of function
start(:).

steps:
Bar() created
execute Bar().start(:slight_smile: with {print(self.object)}
pass closure {print(self.object)} to start(:slight_smile:
closure runs inside of function start(:slight_smile:
closure released after its execution
start(:slight_smile: finished
Bar() released

Zhaoxin

···

On Sat, Jul 2, 2016 at 6:06 AM, Grzegorz Leszek via swift-users < swift-users@swift.org> wrote:

Hello Swift Community,

According to the Swift Programming Language Book:

“A strong reference cycle can also occur if you assign a closure to a
property of a class instance, and the body of that closure captures
the instance.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/pl/jEUH0.l

Does it mean that example below is valid? ( no need to use capture list ):

import Swift

class A {}

class Foo {
    var object = A()
    func bar() {
        Bar().start {
            print(self.object)
        }
    }
}

class Bar {
    func start(completion: () -> ()) {
        completion()
    }
}

As far as I understand, Leak will occur when class Bar stores
completion in the property. But are there any other edge cases ?

Regars,
Greg Leszek
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users