In sub-controller A of Navtionviewcontroller, a B control is used as its property, a block of the B control is defined, and the properties of the a controller are referenced in this block, and the block captures a at this time, forming an indirect circular reference.
Navtionviewcontroller A
A->b
B->blcok
Block--A.someprops = = = Block =>a
Even if the user exits the a controller, that is, the a controller calls the Pop method, that is, Navtionviewcontroller no longer references a, but the block of B still refers to a, when an instance of a is also stored in memory and will not be freed. There's a memory leak.
Workaround, when defining a block, use [weak self] or [unowned self] in front of its arguments.
How do I choose a weak reference or a non-primary reference?
When the instances of closures and captures are always referencing each other and are always destroyed at the same time, the captures within the closures are defined as non-primary references (using [unowned Self]).
Conversely, when a capture reference is sometimes possible nil
, the capture inside the closure is defined as a weak reference (using [weak self]). A weak reference is always an optional type, and when the referenced instance is destroyed, the value of the weak reference is automatically set to nil
. This allows us to check if they exist within the closures.
Problems with block circular referencing in Swift