ios - About strong reference cycles for closures in Swift -


i have defined class called person. code:

    class person {          var closure: (() -> ())?         var name: string          init(name: string) {              self.name = name             print("\(name) being initialized")         }          deinit {             print("\(name) being deinitialized")         }     } 

then use person in class called viewcontroller:

class viewcontroller: uiviewcontroller {      var person = person(name: "john")     let astr = "john cute boy"       override func viewdidload() {         super.viewdidload()          person.closure = {             print("\(self.astr)")         }         person.closure!()     } } 

in opinion, picture of memory code : memory

so, above picture, in opinion, cause strong reference cycle between 3 instances, can not leak instruments, have confusion.

does code cause strong reference cycle?

if not, when arc deallocate instance of person? method named deinit in person class never called.

yes, this's typical retain cycle.

to solve problem use [weak self] in closure

person.closure = { [weak self] in     guard let strongself = self else { return }     print("\(strongself.astr)") } 

to create leak.
create demo app. root navcontroller.
navcontroller has root controller. let's call buttoncontroller. when click button in buttoncontroller, create viewcontroller , push navcontroller. when click button in navigation bar, navcontroller pop viewcontroller instance.

profile it, see leak , retain cycle in instruments.

xcode default template of ios app use single page, retain viewcontroller instance. if viewcontroller instance still used system, it's not leak yet. push & pop show leak you.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -