How do I create a CFUUID NSString under ARC that doesn't leak?

automatic-ref-counting, ios, iphone, objective-c

Solution

You want a "bridged transfer":

+ (NSString *)GetUUID
{
  CFUUIDRef theUUID = CFUUIDCreate(NULL);
  CFStringRef string = CFUUIDCreateString(NULL, theUUID);
  CFRelease(theUUID);
  return (__bridge_transfer NSString *)string;
}

The Transitioning to ARC Guide says

`__bridge_transfer` or `CFBridgingRelease()` moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.

However! You should also rename your method. ARC uses method name conventions to reason about retain counts, and methods that start with `get` in Cocoa have a specific meaning involving passing a buffer in for it to get filled with data. A better name would be `buildUUID` or another word that describes the use of the UUID: `pizzaUUID` or `bearUUID`.

Problem

There are a couple good examples on SO about CFUUID, notably this one: How to create a GUID/UUID using the iPhone SDK But it was made for pre-ARC code, and I'm not a CF junkie (yet), so can someone provide example code that works with ARC? ``` + (NSString *)GetUUID { CFUUIDRef theUUID = CFUUIDCreate(NULL); CFStringRef string = CFUUIDCreateString(NULL, theUUID); CFRelease(theUUID); return [(NSString *)string autorelease]; } ```

Original source

Related problems