Reputation: 1226
When use closure we can avoid strong reference cycle by using weak
or unowned
for capture list.
I know that the function is also a named closure. So I guess function also capture values from the context.
How can I avoid strong reference cycle for function?
class Person {
var name: String?
func printInfo() {
print(self.name ?? "nil")
}
deinit {
print("\(self.name ?? "") is deinitialized.")
}
}
var p1: Person? = Person()
p1?.name = "Person1"
var printFunction = p1?.printInfo
p1 = nil
Not print any message
...
p1 = nil
printFunction = nil
print Person1 is deinitialized.
Does anyone have a solution to this case? In closure case we have weak
, unowned
capture list.
Upvotes: 1
Views: 744
Reputation: 687
You can replace the method with a closure.
class Person {
var name: String?
lazy var printInfo = { [unowned self] in
print(self.name ?? "nil")
}
deinit {
print("\(self.name ?? "") is deinitialized.")
}
}
var p1: Person? = Person()
p1?.name = "Person1"
var printFunction = p1?.printInfo
p1 = nil
This code print - Person1 is deinitialized.
lazy ensures that the access to the property will occur exactly after the initialization of the instance, so the self
will definitely exist and we can use the self
in the closure body.
if you need more information read about ARC - https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html
Upvotes: 1