Create a UUID string with ARC enabled

I need to generate a UUID string in some code with ARC enabled.

After doing some research, this is what I came up with:

CFUUIDRef uuid = CFUUIDCreate(NULL); NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid); CFRelease(uuid); 

Am I using __bridge_transfer correctly to avoid leaking any objects in ARC?

+71
objective-c automatic-ref-counting
Dec 30 '11 at 10:11
source share
3 answers

Looks good. This is what I use (available as gist )

 - (NSString *)uuidString { // Returns a UUID CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault); NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid); CFRelease(uuid); return uuidString; } 

Edited to add

If you are on OS X 10.8 or iOS 6, you can use the new NSUUID class to generate the UUID string without having to go to Core Foundation:

 NSString *uuidString = [[NSUUID UUID] UUIDString]; // Generates: 7E60066C-C7F3-438A-95B1-DDE8634E1072 

But basically, if you just want to create a unique string for a file or directory name, you can use the NSProcessInfo globallyUniqueString method, for example:

 NSString *uuidString = [[NSProcessInfo processInfo] globallyUniqueString]; // generates 56341C6E-35A7-4C97-9C5E-7AC79673EAB2-539-000001F95B327819 

This is not a formal UUID, but it is unique to your network and your process and is a good choice for many cases.

+102
May 6 '12 at 8:32 AM
source share

It looks right to me.

You have CFRelease'd uuid , for which you are responsible for CFUUIDCreate()

And you transferred ownership of the string to ARC, so the compiler knows to free uuidStr at the appropriate time.

+42
Dec 30 '11 at 22:17
source share

From clang docs :

(__bridge_transfer T) op specifies the operand, which must have a non-persistent pointer type, to the destination type, which must be the type of the object's persistent type. ARC returns the value at the end of the encompassing full expression, taking into account normal local value optimizations.

So you are doing it right.

+7
Dec 30 '11 at 10:16
source share



All Articles