What's the difference between takeUnretainedValue
and takeRetainedValue
? Based on Apple's documentation:
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.
But how do I know whether the unmanaged object is an unretained or retained object? For instance, the method ABAddressBookCreateWithOptions:
from AddressBook
framework returns an unmanaged object ABAddressBook
, which some tutorials consider this as a retained object. When using ALAsset
, the method thumbnail
returns an unmanaged object CGImage
, which some tutorials consider this as a unretained object.
I'll appreciate your help.
how do I know whether the unmanaged object is an unretained or retained object?
It depends on which API you use.
There are some Conventions here: Ownership Polocy / Memory Management Programming Guide for Core Foundation
Basically, if a function name contains the word "Create" or "Copy", use .takeRetainedValue()
. If a function name contains the word "Get", use .takeUnretainedValue()
.
And, if it does not contains either, as far as I know, we can still use .takeUnretainedValue()
in almost every cases.
However, every rule has an exception :) for example, see:
Swift UnsafeMutablePointer<Unmanaged<CFString>?> allocation and print