您不希望使用<条码>[自有]条码>。 有时,你们想要关闭是为了自我控制,以确保封锁在要求关闭时仍然前后。
Example: Making an asynchronous network request
如果您提出星座网络要求,请您do在申请完成时要求关闭<代码>自封/代码>。 否则,该物体可能已经停用,但你仍然希望能够处理完成申请。
When to use unowned self
or weak self
The only time where you really want to use [unowned self]
or [weak self]
is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around.
在关闭的具体情况下,你必须认识到,在封闭状态中提及的任何变数都“拥有”。 只要封锁环绕,这些物体就得到保证。 停止这种所有权的唯一途径是填写<代码>[非自有]或[weak self]
。 因此,如果某个阶层拥有关闭权,而关闭则能有力地提及这一类别,那么,在关闭和关闭类别之间,你就有一个强有力的参照周期。 这也包括,如果该阶级拥有一些拥有封锁的物品。
Specifically in the example from the video
In the example on the slide, TempNotifier
owns the closure through the onChange
member variable. If they did not declare self
as unowned
, the closure would also own self
creating a strong reference cycle.
Difference between unowned
and weak
The difference between unowned
and weak
is that weak
is declared as an Optional while unowned
is not. By declaring it weak
you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned
variable that happens to be nil, it will crash the whole program. So only use unowned
when you are positive that variable will always be around while the closure is around