3

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.

Aнгел
  • 1,361
  • 3
  • 17
  • 32

1 Answers1

8

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

Community
  • 1
  • 1
rintaro
  • 51,423
  • 14
  • 131
  • 139
  • this is a good, simple, and to-the-point explanation :) Thanks! So, in my case, because `ALAsset` method `someALAsset.defaultRepresentation().fullScreenImage()` returns an unmanaged `CGImage` then I should use `.takeUnretainedValue()`, correct? I mean, `CGImage` doesn't contain "create" or "copy" in its constructor. – Aнгел Mar 25 '15 at 18:38
  • Correct, `fullScreenImage` does not contain "Create" or "Copy". If you are unsure which to use, you might want to find some sample codes in apple.com. For example, [this sample](https://developer.apple.com/library/ios/samplecode/PrintPhoto/Listings/Classes_PrintPhotoViewController_m.html) is using `fullScreenImage`, but not releasing the result with `CGImageRelease`. – rintaro Mar 26 '15 at 02:22