Swift delegation - when to use weak pointer on delegate

后端 未结 3 1807
死守一世寂寞
死守一世寂寞 2020-12-07 18:38

Can someone explain when and when not to use a \'weak\' assignment to a delegate pointer in Swift, and why?

My understanding is that if you use a protocol that is n

3条回答
  •  没有蜡笔的小新
    2020-12-07 19:28

    Delegates should (edit: generally) always be weak.

    Lets say b is the delegate of a. Now a's delegate property is b.

    In a case where you want b to release when c is gone

    If c holds a strong reference to b and c deallocates, you want b to deallocate with c. However, using a strong delegate property in a, b will never get deallocated since a is holding on to b strongly. Using a weak reference, as soon as b loses the strong reference from c, b will dealloc when c deallocs.

    Usually this is the intended behaviour, which is why you would want to use a weak property.

提交回复
热议问题