How to create CFUUID NSString in ARC that does not leak?

There are some good examples on SO about CFUUID, especially this one:

How to create a GUID / UUID using the iPhone SDK

But this was done for pre-ARC code, and I am not a CF addict (yet), so can anyone provide an example of code that works with ARC?

+ (NSString *)GetUUID { CFUUIDRef theUUID = CFUUIDCreate(NULL); CFStringRef string = CFUUIDCreateString(NULL, theUUID); CFRelease(theUUID); return [(NSString *)string autorelease]; } 
+7
source share
3 answers

You need a "bridge":

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

Transition to ARC Guide says

__bridge_transfer or CFBridgingRelease() moves the non-Objective-C pointer to Objective-C, and also transfers ownership of the ARC.

But! You must also rename your method. ARC uses method naming conventions to determine hold values, and methods starting with get in Cocoa have a specific meaning of passing a buffer to fill data. The best name would be buildUUID or another word that describes the use of UUID: pizzaUUID or bearUUID .

+23
source

Assuming you no longer need to support iOS up to 6.0 at the moment, you can skip all the UUID Core Foundation stuff and just do it to get a new one:

 NSString * uuidStr = [[NSUUID UUID] UUIDString]; 
+5
source

Single line:

 NSString *UUID = CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, CFUUIDCreate(NULL))); 
0
source

All Articles