takeUnretainedValue 和 takeRetainedValue 有什么区别?

What's the difference between takeUnretainedValue and takeRetainedValue?

takeUnretainedValuetakeRetainedValue 有什么区别?基于 Apple 的文档:

Both of these methods return the original, unwrapped type of the object. You choose which method to use based on whether the API you are invoking returns an unretained or retained object.

但是我怎么知道非托管对象是未保留对象还是保留对象呢?例如,来自 AddressBook 框架的方法 ABAddressBookCreateWithOptions: returns 一个非托管对象 ABAddressBook,一些教程将其视为保留对象。当使用 ALAsset 时,方法 thumbnail returns 一个非托管对象 CGImage,一些教程认为这是一个未保留的对象。

非常感谢你的帮助。

how do I know whether the unmanaged object is an unretained or retained object?

这取决于您使用的 API。

这里有一些约定:Ownership Polocy / Memory Management Programming Guide for Core Foundation

基本上,如果函数名称包含单词 "Create" 或 "Copy",请使用 .takeRetainedValue()。如果函数名称包含单词 "Get",请使用 .takeUnretainedValue().

而且,如果它不包含任何一个,据我所知,我们仍然可以在几乎所有情况下使用 .takeUnretainedValue()

但是,每条规则都有例外:) 例如,参见:
Swift UnsafeMutablePointer<Unmanaged<CFString>?> allocation and print