Why specify [unowned self] in blocks where you depend on self being there?

后端 未结 5 1519
后悔当初
后悔当初 2021-01-19 01:37

I want self to be non-nil and I\'m sure it will be, during the blocks execution. So why explicitly specify [unowned self] ?

object.executeBlock {
    date =         


        
5条回答
  •  天涯浪人
    2021-01-19 02:30

    Why [unowned self]? self points to object, object has executeBlock, and executeBlock points back to self, creating a memory cycle.

    However when you say [unowned self]: the system will not keep self in memory in order to to make the closure work. it will assume that self is always there when the closure is executed. If not for some reason, there won't be undefined behavior or anything like that but your app will crash as it is a runtime error.

    This is how it was explained by Paul Hegarty, stanford iOS dev teacher.

提交回复
热议问题