Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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];
}
like image 494
TigerCoding Avatar asked May 07 '12 03:05

TigerCoding


2 Answers

Assuming you no longer need to support iOS prior to 6.0 at this point, you can skip all the Core Foundation UUID stuff and just do this to get a fresh one:

NSString * uuidStr = [[NSUUID UUID] UUIDString];
like image 43
Ben Zotto Avatar answered Sep 17 '22 13:09

Ben Zotto


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.

like image 132
jscs Avatar answered Sep 20 '22 13:09

jscs