生成启用 ARC 的 UUID 字符串
我需要在启用 ARC 的某些代码中生成 UUID 字符串。
经过一些研究后,我得出的结论是:
CFUUIDRef uuid = CFUUIDCreate(NULL);
NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
我是否正确使用 __bridge_transfer 来避免泄漏 ARC 下的任何对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对我来说看起来不错。这就是我使用的(可作为要点)
编辑添加
如果您使用的是 OS X 10.8或者 iOS 6 您可以使用新的 NSUUID 类生成字符串 UUID,无需前往核心基础:
但大多数情况下,如果您只想为文件或目录名称生成唯一的字符串,那么您可以使用 NSProcessInfo 的 globallyUniqueString 方法,例如:
它不是正式的 UUID,但对于您的网络和进程来说是唯一的,并且在很多情况下都是不错的选择。
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.
这对我来说看起来是正确的。
您拥有 CFRelease 的
uuid
,这是您在CFUUIDCreate()
中负责的,并且您已将字符串的所有权转移给 ARC,因此编译器知道要释放
uuidStr
在适当的时间。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.来自 clang 文档:
所以你做得对。
From clang docs:
So you are doing it right.