< 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 reference counted environment. The semantics are different if you are using garbage collection—see Garbage Collection Programming Guide.

Core Foundation's memory allocation policy is that you need to release values returned by functions with “Copy” or “Create” in their name; you should not release values returned by functions that do not have “Copy” or “Create” in their name.

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.

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


© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-05-06)


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.