rustyshelf
rustyshelf

Reputation: 45101

How to create a GUID/UUID using iOS

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?

Upvotes: 213

Views: 124390

Answers (8)

Radu Diță
Radu Diță

Reputation: 14171

In Swift 3.0

var uuid = UUID().uuidString

Upvotes: 20

Stephan Burlot
Stephan Burlot

Reputation: 5077

[[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];

Upvotes: 325

King-Wizard
King-Wizard

Reputation: 15694

In Swift:

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

Upvotes: 24

Henk
Henk

Reputation: 1704

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

Upvotes: 46

tumtumtum
tumtumtum

Reputation: 1162

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.

Upvotes: 7

Arian Sharifian
Arian Sharifian

Reputation: 1295

In iOS 6 you can easily use:

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

More details in Apple's Documentations

Upvotes: 93

trillions
trillions

Reputation: 3709

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;
}

Upvotes: 101

Ryan McCuaig
Ryan McCuaig

Reputation: 2279

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

Upvotes: 22

Related Questions