iOS Reference Library Apple Developer
Search

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.




Last updated: 2010-06-24

Did this document help you? Yes It's good, but... Not helpful...