1.18. Typecasting with Automatic Reference Counting
Problem
You want to know how to use new typecasting facilities under Automatic Reference Counting in order to avoid memory leaks when working with Core Foundation objects inside your Objective-C code.
Solution
Use the __bridge, __bridge_transfer, and __bridge_retained typecasting
specifiers.
Discussion
Typecasting is the process of pointing one value of type A to
another value of type B. For instance, if you have a Core Foundation
string object of type CFStringRef
and you would like to place it inside an Objective-C string of type
NSString, you can easily create an
error:
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
CFStringRef coreFoundationString =
CFStringCreateWithCString(CFAllocatorGetDefault(),
"C String",
kCFStringEncodingUTF8);
/* Compile time error!!! */
NSString *objCString = coreFoundationString;
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}Here we are assigning the value of the Core Foundation string
coreFoundationString to the
Objective-C string of type NSString
named objCString, our compiler will get confused because it doesn’t know what we are intending to do with the memory assigned to each one of these objects. Additionally, we will end up with a memory leak because the compiler doesn’t know how to get rid of the Core Foundation ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access