How to create a GUID/UUID using iOS

IosUuidGuid

Ios Problem Overview


I want to be able to create a GUID/UUID on the iPhone and iPad.

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 Solutions


Solution 1 - Ios

[[UIDevice currentDevice] uniqueIdentifier]

Returns the Unique ID of your iPhone.

> 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.

If you need to create several UUID, just use this method (with 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:

NSString *UUID = [[NSUUID UUID] UUIDString];

Solution 2 - Ios

Here is the simple code I am using, compliant with ARC.

+(NSString *)getUUID
{
    CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
    NSString * uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
    CFRelease(newUniqueId);

    return uuidString;
}

Solution 3 - Ios

In iOS 6 you can easily use:

NSUUID  *UUID = [NSUUID UUID];
NSString* stringUUID = [UUID UUIDString];

More details in Apple's Documentations

Solution 4 - Ios

Reviewing the Apple Developer documentation I found the CFUUID object is available on the iPhone OS 2.0 and later.

Solution 5 - Ios

In Swift:

var uuid: String = NSUUID().UUIDString
println("uuid: \(uuid)")

Solution 6 - Ios

The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]. See the NSProcessInfo class reference.

Solution 7 - Ios

In Swift 3.0

var uuid = UUID().uuidString

Solution 8 - Ios

I've uploaded my simple but fast implementation of a Guid class for ObjC here: obj-c GUID

Guid* guid = [Guid randomGuid];
NSLog("%@", guid.description);

It can parse to and from various string formats as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrustyshelfView Question on Stackoverflow
Solution 1 - IosStephan BurlotView Answer on Stackoverflow
Solution 2 - IostrillionsView Answer on Stackoverflow
Solution 3 - IosArian SharifianView Answer on Stackoverflow
Solution 4 - IosHenkView Answer on Stackoverflow
Solution 5 - IosKing-WizardView Answer on Stackoverflow
Solution 6 - IosRyan McCuaigView Answer on Stackoverflow
Solution 7 - IosRadu DițăView Answer on Stackoverflow
Solution 8 - IostumtumtumView Answer on Stackoverflow