ios - How memory leak will occur in swift? -


i new ios development , want learn how memory leak occur in swift or in objective-c, can 1 explain small example?

thanks

small example:

class {     var b: b!      deinit {         print("deinit of a")     } }  class b {     var a: a!      deinit {         print("deinit of b")     } }  {     let = a()     let b = b()     a.b = b     b.a = } 

if run code (maybe in playground), print nothing. means deinit never called both objects , leaked.

but if declare 1 of properties weak:

class {     weak var b: b!      deinit {         print("deinit of a")     } } 

then deinit called , you'll see messages in console.

edit: add example closures

consider example:

class c {     var f: (void -> void)!      deinit {         print("deinit c")     } }  {     let c = c()     c.f = {         print(c)     } } 

c captures f, f captures c. got memory leak.

to deal leaks in closures, have 2 options – declare captured object weak or unowned. this:

do {     let c = c()     c.f = { [weak c] in         print(c)     } } 

basically, use weak if it's possible object out of existence , become nil when closure called; if sure object still exist @ time, use unowned instead.

after declare c weak inside closure, "deinit c" printed – means deallocated successfully.

what means you, developer?

almost time don't have worry memory management. it's done you, automatically. objects exist when need them , vanish when don't. there 2 common cases when need careful , think memory.

  1. delegation. it's common pattern in cocoa , create retain cycles if done wrong. declare delegate weak unless have reason not to.
  2. closures. closure capture references objects in surrounding scope , automatically, without notice. when implementing closure, chech if create retain cycle. if yes, declare problem variables weak or unowned.

for further info suggest read official apple swift book can found in ibooks or here website.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -