如何使用 iOS 创建 GUID/UUID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/427180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a GUID/UUID using iOS
提问by rustyshelf
I want to be able to create a GUID/UUID on the iPhone and iPad.
我希望能够在 iPhone 和 iPad 上创建 GUID/UUID。
The intention is to be able to create keys for distributed data that are all unique. Is there a way to do this with the iOS SDK?
目的是能够为所有唯一的分布式数据创建密钥。有没有办法用 iOS SDK 做到这一点?
回答by Stephan Burlot
[[UIDevice currentDevice] uniqueIdentifier]
Returns the Unique ID of your iPhone.
返回 iPhone 的唯一 ID。
EDIT:
-[UIDevice uniqueIdentifier]
is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.
编辑:
-[UIDevice uniqueIdentifier]
现在已弃用,应用程序被 App Store 拒绝使用它。下面的方法现在是首选方法。
If you need to create several UUID, just use this method (with ARC):
如果您需要创建多个 UUID,只需使用此方法(使用 ARC):
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string;
}
EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:
编辑:2014 年 1 月 29 日:如果您的目标是 iOS 6 或更高版本,您现在可以使用更简单的方法:
NSString *UUID = [[NSUUID UUID] UUIDString];
回答by trillions
Here is the simple code I am using, compliant with ARC.
这是我正在使用的简单代码,符合 ARC。
+(NSString *)getUUID
{
CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
NSString * uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
CFRelease(newUniqueId);
return uuidString;
}
回答by Arian Sharifian
In iOS 6 you can easily use:
在 iOS 6 中,您可以轻松使用:
NSUUID *UUID = [NSUUID UUID];
NSString* stringUUID = [UUID UUIDString];
More details in Apple's Documentations
Apple 文档中的更多详细信息
回答by Henk
回答by King-Wizard
In Swift:
在斯威夫特:
var uuid: String = NSUUID().UUIDString
println("uuid: \(uuid)")
回答by Ryan McCuaig
The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]
. See the NSProcessInfoclass reference.
最简单的技术是使用NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]
. 请参阅NSProcessInfo类参考。
回答by Radu Di??
In Swift 3.0
在Swift 3.0 中
var uuid = UUID().uuidString
回答by tumtumtum
I've uploaded my simple but fast implementation of a Guid class for ObjC here: obj-c GUID
我在此处上传了 ObjC 的 Guid 类的简单但快速的实现:obj-c GUID
Guid* guid = [Guid randomGuid];
NSLog("%@", guid.description);
It can parse to and from various string formats as well.
它也可以解析各种字符串格式。