本文介绍了取消初始化时,未拥有的引用是否设置为"nil"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很快就对这个话题感到困惑,因为据说无主引用必须始终具有一个值并且不能是可选的,这也意味着它们不能设置为"nil". Apple迅速将实例'B'取消初始化/取消分配之后,Apple文档迅速将实例'A'引用了实例'B'并取消分配……当var被取消初始化/取消分配时,它不是吗?意味着它们设置为无" ????实例B是可选的,因此请确保它可以容纳'nil',但是为什么实例'A'在应该始终具有值的情况下被取消初始化?

PS:如果有帮助.....实例'B'是一个可选类型,其中强烈引用了实例'A'

解决方案

unowned引用的要点是保留对要保证的内容的弱引用(基于您的应用程序逻辑),该内容在发布之前不会被释放.具有unowned引用的对象.您可以在文档中了解更多信息.

从某种意义上说,这与隐式解包的可选类型(例如String!)类似.您告诉编译器,当它为nil时,您将永远无法访问该值,如果这样做,您的程序将崩溃.

I'm confused on this topic in swift where it is said that unowned references must always have a value and cannot be optional, also meaning they cannot be set to 'nil'....well I just saw a program on the Apple documents for swift that instance 'A' with an unowned reference to instance 'B' was deinitialized and deallocated right after instance 'B' was deinitialized/deallocated......when a var is deinitialzed/dealloc doesn't it mean they are set to 'nil'??? Instance B is an optional so sure it can hold 'nil' but why did instance 'A' get deinitialized when its supposed to always have a value????

PS: If this helps..... instance 'B' was an optional type with a strong reference to instance 'A'

解决方案

The point of an unowned reference is to hold a weak reference to something that you are guaranteeing (based on your application logic) will not be deallocated prior to the object that has the unowned reference. You can read more in the documentation.

In a sense it is a similar thing to an implicitly unwrapped optional type (such as String!). You're telling the compiler that you won't ever access the value when it is nil, and if you do your program will crash.

这篇关于取消初始化时,未拥有的引用是否设置为"nil"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:52