本文介绍了Swift中“无主(安全)"和“无主(安全)"有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple的 Swift编程语言指南 提到了捕获说明符 unowned(safe)unowned(unsafe),以及weakunowned.

我(认为我)了解weakunowned之间的区别;但是unowned(safe)unowned(unsafe)有什么区别?指南没有说.


请:不要仅仅简单地声明与Objective-C等效的内容.

解决方案

据我了解,虽然我找不到苹果公司的权威消息,但unowned可以分为两种口味,safe和.

裸露的unownedunowned(safe):这是一个特殊包装的引用,当引用已取消分配的实例时,它将引发异常.

特殊情况是unowned(unsafe):它与Objective C的@property (assign)__unsafe_unretained的Swift等效.不应在Swift程序中使用它,因为它的目的是桥接到用Objective C编写的代码.

因此,在查看Cocoa类的导入包装时,您会看到unowned(unsafe),但是除非需要,否则不要使用它,并且您会知道何时需要.


更新

__unsafe_unretained是一个简单的指针.它不会知道所指向的实例何时被取消分配,因此,当它被取消引用时,基础内存可能是垃圾.

如果存在使用已分配的__unsafe_unretained变量的缺陷,您将看到不稳定的行为.有时足够的内存位置足以使代码运行,有时它将被部分覆盖,因此您会遇到非常奇怪的崩溃,并且有时该内存位置将包含一个新对象,因此您将获得无法识别的选择器异常. >

过渡到ARC发行说明

Apple's Swift Programming Language Guide mentions the capture specifiers unowned(safe) and unowned(unsafe), in addition to weak and unowned.

I (think I) understand the differences between weak and unowned; but what is the difference between unowned(safe) and unowned(unsafe)? The guide doesn't say.


Please: Don't rely on simply stating an Objective-C equivalent.

解决方案

From what I understand, although I can't find a definitive source from Apple, unowned can be broken into two flavors, safe and unsafe.

A bare unowned is unowned(safe): it is a specially wrapped reference which will throw an exception when a dealloced instance is referenced.

The special case is unowned(unsafe): it is the Swift equivalent of Objective C's @property (assign) or __unsafe_unretained. It should not be used in a Swift program, because its purpose is to bridge to code written in Objective C.

So, you will see unowned(unsafe) when looking at the import wrapper for Cocoa classes, but don't use it unless you have to, and you will know when you have to.


Update

__unsafe_unretained is a simple pointer. It will not know when the instance being pointed at has be dealloced, so when it's dereferenced, the underlying memory could be garbage.

If you have a defect where a dealloced __unsafe_unretained variable is being used, you will see erratic behavior. Sometimes enough of that memory location is good enough so the code will run, sometimes it will have been partially overwritten so you will get very odd crashes, and sometimes that memory location will contain a new object so you will get unrecognized selector exceptions.

Transitioning to ARC Release Notes

这篇关于Swift中“无主(安全)"和“无主(安全)"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 10:05