如何在Objective-C中获取UUID,就像Java中使用UUID生成代表128位值的唯一随机数。
如何在Objective-C中获取UUID,就像Java中使用UUID生成代表128位值的唯一随机数。
尝试:
CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *udidString = (NSString *) CFUUIDCreateString(NULL, udid);
更新:
从iOS 6开始,有一种更简单的方法来生成UUID。像往常一样,有多种方法可以实现:
创建一个UUID字符串:
NSString *uuid = [[NSUUID UUID] UUIDString];
创建一个UUID:
[NSUUID UUID]; // which is the same as..
[[NSUUID] alloc] init];
创建一个NSConcreteUUID
类型对象,可以轻松转换为NSString
,格式如下:BE5BA3D0-971C-4418-9ECF-E2D1ABCB66BE
文档说明:
注意:NSUUID类与CoreFoundation的CFUUIDRef不是toll-free bridged。 如有需要,请使用UUID字符串在CFUUID和NSUUID之间进行转换。 两个NSUUID对象不能保证通过指针值(如CFUUIDRef)进行比较; 使用isEqual:来比较两个NSUUID实例。
+ (NSString *)uniqueFileName
{
CFUUIDRef theUniqueString = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUniqueString);
CFRelease(theUniqueString);
return [(NSString *)string autorelease];
}
-(NSString*) myUUID()
{
CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID);
NSString *guid = (__bridge NSString *)newUniqueIDString;
CFRelease(newUniqueIDString);
CFRelease(newUniqueID);
return([guid lowercaseString]);
}
- (NSString*)generateGUID{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [NSString stringWithFormat:@"%@", string];
}
对于Swift 5.0,请使用以下内容:
let uuidRef = CFUUIDCreate(nil)
let uuidStringRef = CFUUIDCreateString(nil, uuidRef)
let uuid = uuidStringRef as String? ?? ""