A Swift call into a C image-decoding library returns Unmanaged<CFData>?; what does that tell you, and how do you choose takeRetainedValue or takeUnretainedValue?
answer
- the header never stated ownership
- Create and Copy versus Get
- +1 or +0 on return
- annotate or audit the header
basics
~20 sUnmanaged means Swift could not tell whether the C function returns an owned (+1) or borrowed (+0) Core Foundation object. Use takeRetainedValue for Create or Copy functions, which hand you ownership, and takeUnretainedValue for Get functions, which do not.
solid answer
~40 sCore Foundation objects are reference counted, and ARC manages them automatically only when Swift knows the function's ownership convention: the declaration is annotated `CF_RETURNS_RETAINED` or `CF_RETURNS_NOT_RETAINED`, or it sits in a `CF_IMPLICIT_BRIDGING_ENABLED` region where the Create/Copy naming rule applies. Otherwise Swift imports the result as `Unmanaged<CFData>`, and `Unmanaged`'s own documentation says you become partially responsible for keeping the object alive. Call `takeRetainedValue()` when the function returned +1 (its name contains Create or Copy): ARC takes over that retain. Call `takeUnretainedValue()` when it returned +0 (a Get function): ARC adds its own retain. Choosing wrong leaks, or over-releases and crashes later. The durable fix is annotating the header, after which the function returns a managed `CFData` that bridges toll-free to `Data` with `as`.
code
swift · 20 lines// From the decoder's C header, imported through the bridging header:
// CFDataRef ImgDecodeCopyPixels(const char *path); // not annotated
// CFDataRef ImgDecodeCachedPixels(const char *path); // not annotated, +0
// CFDataRef ImgDecodeMakePixels(const char *path) CF_RETURNS_RETAINED;
import Foundation
func loadPixels(path: String) -> Data? {
// Imported as Unmanaged<CFData>?: Swift does not know the convention.
guard let unmanaged = ImgDecodeCopyPixels(path) else { return nil }
let pixels: CFData = unmanaged.takeRetainedValue() // "Copy" returned +1
return pixels as Data // toll-free bridging
}
func cachedPixels(path: String) -> CFData? {
ImgDecodeCachedPixels(path)?.takeUnretainedValue() // library keeps ownership
}
func madePixels(path: String) -> CFData? {
ImgDecodeMakePixels(path) // annotated: already managed
}go deeper
Recall that Unmanaged appears when Swift does not know who owns a returned Core Foundation object, and that Create or Copy means you own it.
Explain +1 versus +0 returns, how takeRetainedValue and takeUnretainedValue map to them, and which header annotations remove Unmanaged.
Diagnose the leak or the late crash a wrong take call causes, and fix it at the header or behind one reviewed Swift wrapper per function.
Decide where ownership knowledge lives for third-party C libraries: annotated headers or a wrapper module, so app code never handles Unmanaged.
## Why Swift sometimes refuses to manage the result Core Foundation (CF) types such as `CFData`, `CFString` and `CFArray` are reference-counted C objects. Swift imports them as classes and lets ARC retain and release them, but ARC must know one fact per function: does the returned object arrive **already retained** (+1, the caller owns it) or **not retained** (+0, someone else owns it)? C has no syntax for that, so the header must say it. | How the C header declares the function | Imported return type | |---|---| | Annotated `CF_RETURNS_RETAINED` | `CFData?`, managed by ARC | | Annotated `CF_RETURNS_NOT_RETAINED` | `CFData?`, managed by ARC | | Inside `CF_IMPLICIT_BRIDGING_ENABLED` ... `CF_IMPLICIT_BRIDGING_DISABLED` | `CFData?`, ownership inferred from the name | | None of the above | `Unmanaged<CFData>?` | Most of Apple's CF-based APIs are annotated, so they return managed objects. A third-party C library often is not, and that is where `Unmanaged` appears. ## What `Unmanaged` is `Unmanaged<Instance>` is a standard-library struct that wraps a class reference **without** ARC touching it. Its documentation is blunt: "When you use this type, you become partially responsible for keeping the object alive." You convert it to a managed reference once, with the call that matches the function's convention: - **`takeRetainedValue()`** "consumes an unbalanced retain": use it when you are responsible for releasing the result, which by the Core Foundation naming convention means the function name contains **Create** or **Copy**. - **`takeUnretainedValue()`** gets the reference "without consuming an unbalanced retain": use it when you are not responsible, typically a **Get** function returning an object owned by something else. ## What goes wrong with the wrong call 1. **`takeUnretainedValue()` on a +1 result**: ARC retains again and later releases once; the original retain is never balanced, so the object **leaks**. 2. **`takeRetainedValue()` on a +0 result**: ARC releases a retain it never owned, so the object can be freed while its real owner still uses it, a use-after-free crash that surfaces somewhere else. 3. **Calling `takeRetainedValue()` twice** on the same `Unmanaged` value consumes the same retain twice, the same over-release. These bugs pass code review easily, because both calls compile and both return a `CFData`. ## The durable fix: annotate the header If you own or vendor the C library's header, add `CF_RETURNS_RETAINED` to each Create or Copy function, or wrap audited sections in `CF_IMPLICIT_BRIDGING_ENABLED`. The functions then import as returning a managed `CFData?`, the `Unmanaged` disappears from every call site, and nobody has to remember the naming rule. Where you cannot edit the header, wrap each function once in a small Swift function that makes the right `take` call, and let the rest of the app use the wrapper. ## Toll-free bridging after that Many CF types are **toll-free bridged** with Foundation classes: `CFData` with `NSData`, `CFString` with `NSString`, `CFArray` with `NSArray`. In Swift this shows up as plain `as` conversions: `cfData as Data`, `cfString as String`, `"photo.heic" as CFString`. Once the value is managed, no `Unmanaged` call is involved; the cast rules themselves belong to the material on casting. ## Unmanaged in the other direction C callback APIs often take a `void *` context. `Unmanaged.passUnretained(object).toOpaque()` turns a Swift object into that pointer without retaining it, and `Unmanaged<T>.fromOpaque(pointer).takeUnretainedValue()` turns it back in the callback. `passRetained` instead adds a retain the C side must balance. The raw-pointer side of this belongs to the material on unsafe pointers. ## Reviewing a new C dependency 1. List every function that returns a CF type and read its name and documentation for the Create, Copy or Get convention. 2. Annotate the header, or write one Swift wrapper per unaudited function that makes the right `take` call. 3. Add nullability annotations as well: CF references are pointers, so an unannotated one may be `NULL`, which is why the example's result is `Unmanaged<CFData>?`. 4. Run the wrappers under the leak and address checkers before the rest of the app calls them. ## The rest of a C header, briefly - A C `struct` imports as a Swift struct with a zero-filling `init()` and a memberwise initializer. - A `#define` of a constant imports as a read-only global; function-like macros are not imported. - A `const char *` parameter accepts a Swift `String` directly at the call site. - A plain C `enum` imports as a `RawRepresentable` struct with each enumerator as a global constant, and a `typedef` of an anonymous struct imports as a Swift struct with that name.
- The C library's header is vendored into your repository; what do you change so call sites stop seeing Unmanaged?Annotate each function with its convention, `CF_RETURNS_RETAINED` for Create or Copy functions and `CF_RETURNS_NOT_RETAINED` for Get functions, or wrap a section that follows the naming rule in `CF_IMPLICIT_BRIDGING_ENABLED` and `CF_IMPLICIT_BRIDGING_DISABLED`. Swift then imports managed `CFData?` results and ARC balances them, with no change to C callers.
- How would you catch a wrong take call before it ships?Name the rule in one place: wrap each unaudited function in a tiny Swift function and review those wrappers against the C library's documentation. Then exercise them under the memory tools: a leak checker shows the +1 taken unretained, and the Address Sanitizer reports the later use-after-free together with where the object was freed.
Unmanaged is a parcel delivered without a note saying whether it is yours to keep. takeRetainedValue says 'it is mine, I will dispose of it'; takeUnretainedValue says 'I am only borrowing it'. Claim a borrowed parcel and you throw away someone else's property; borrow your own and it piles up forever.
- ARC manages every Core Foundation object returned by a C function automatically.
- takeRetainedValue and takeUnretainedValue differ only in performance.
- Calling takeRetainedValue twice on one Unmanaged value is harmless.
- Unmanaged return types mean the C function can never return NULL.
- A CFData needs a manual byte copy before it can become Data.