Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

< Previous PageNext Page > Hide TOC

Memory Management of Core Foundation Objects in Cocoa

A number of Core Foundation and Cocoa instances can simply be type-cast to each other, such as CFString and NSString objects. This document explains how to manage Core Foundation objects in Cocoa. See “Object Ownership and Disposal” for general information on object ownership.

Important: This article describes using Cocoa and Core Foundation in a managed memory environment. The semantics are different if you are using garbage collection—see Garbage Collection Programming Guide.

Core Foundation's memory allocation policy is that functions with “Copy” or “Create” in their name return values the caller needs to release; all other functions return values you should not release.

In Cocoa, objects created with “alloc”, “copy” , or “new” functions or methods need to be released by the caller.

The conventions used by both Core Foundation and Cocoa are very similar, and because the allocation/retain/release implementations are compatible, equivalent functions and methods from each environment can be used in an intermixed fashion. So,

NSString *str = [[NSString alloc] initWithCharacters: ...];
...
[str release];

is equivalent to

CFStringRef str = CFStringCreateWithCharacters(...);
 ...
CFRelease(str);

and

NSString *str = (NSString *)CFStringCreateWithCharacters(...);
 ...
[str release];

and

 NSString *str = (NSString *)CFStringCreateWithCharacters(...);
 ...
 [str autorelease];

As these code samples show, once created, the type-casted objects can be treated as Cocoa or Core Foundation and look “native” in each environment.

It has been observed that a larger percentage of Core Foundation functions tend to be “Create” or “Copy” functions when compared to Cocoa’s “alloc”, “copy”, or “new” functions and methods, so it is important to remember to release or autorelease Core Foundation-created objects if appropriate.

Additional information about working with Core Foundation and Carbon data types can be found in the Interchangeable Data Types section of Carbon-Cocoa Integration Guide.



< Previous PageNext Page > Hide TOC


Last updated: 2008-02-08




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice