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 correctly using __bridge_transfer
to avoid leaking any objects under ARC?
Looks fine to me. This is what I use (available as a gist)
Edited to add
If you are on OS X 10.8 or iOS 6 you can use the new NSUUID class to generate a string UUID, without having to go to Core Foundation:
But mostly, if you just want to generate a unique string for a file or directory name then you can use
NSProcessInfo
'sgloballyUniqueString
method like:It's not a formal UUID, but it is unique for your network and your process and is a good choice for a lot of cases.
That looks correct to me.
You have CFRelease'd
uuid
, which is your responsibility from theCFUUIDCreate()
And you've transferred ownership of the string to ARC, so the compiler knows to release
uuidStr
at the appropriate time.From clang docs:
So you are doing it right.