December 2018
Intermediate to advanced
414 pages
10h 19m
English
Functions and closures can capture the current scope, which means all of the declared variables outside of the function or closure definition, such as local variables or self. In the case of self, you can inadvertently extended the lifetime of your objects and leak memory:
class MyClass { var running = false func run() { running = true DispatchQueue.main.asyncAfter(deadline: .now() + 10) { self.running = false } }}var instance: MyClass? = MyClass()instance?.run()instance = nil
Can you spot the potential issue in this code?
Depending on the use case, you may want instance to be destroyed when it is not referenced by any owner. In our case, we'll probably cause a memory leak, as the dispatch block is referencing ...
Read now
Unlock full access