生成启用了ARC的UUID字符串 [英] Generate a UUID string with ARC enabled
问题描述
我需要在启用了ARC的某些代码中生成UUID字符串.
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);
我是否正确使用__bridge_transfer
以避免在ARC下泄漏任何对象?
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)
- (NSString *)uuidString {
// Returns a UUID
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
CFRelease(uuid);
return uuidString;
}
编辑后添加
如果您使用的是OS X 10.8或iOS 6,则可以使用新的
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:
NSString *uuidString = [[NSUUID UUID] UUIDString];
// Generates: 7E60066C-C7F3-438A-95B1-DDE8634E1072
但是,大多数情况下,如果您只想为文件或目录名称生成唯一的字符串,则可以使用NSProcessInfo
的globallyUniqueString
方法,例如:
But mostly, if you just want to generate a unique string for a file or directory name then you can use NSProcessInfo
's globallyUniqueString
method like:
NSString *uuidString = [[NSProcessInfo processInfo] globallyUniqueString];
// generates 56341C6E-35A7-4C97-9C5E-7AC79673EAB2-539-000001F95B327819
这不是正式的UUID,但对于您的网络和过程来说是唯一的,并且在许多情况下都是不错的选择.
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.
这篇关于生成启用了ARC的UUID字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!