Create Universally Unique Identifier (UUID) The iOS 6 Way

With iOS 6 release, Apple introduced a new class to create universally unique identifiers (UUID) aka globally unique identifiers (GUID).

The class NSUUID implements RFC 4122 creating values that are 128 bits long and guaranteed to be unique across space and time by using a unique value on the device as well as a value representing the elapsed time since October 15, 1582 at 00:00:00.

Here is how to generate a UUID in iOS 6:

// Get UUID value
// Convert UUID to string and output result
NSLog(@"UUID: %@", [uuid UUIDString]);

The output looks something like this:

UUID: A84AFC3C-B3A7-31C7-B3E9-234AF423C6B1

  1. Nice, thanks!
    But how to keep iOS 5 backward compatibility?

    • This is the equivalent code for iOS 5 and earlier:

      CFUUIDRef uuid = CFUUIDCreate(NULL);
      CFStringRef identifier = CFUUIDCreateString(NULL, uuid);

      NSString *uuidString = CFBridgingRelease(identifier);

  2. I m getting different identifier in ios5.0 and iOS 6.0, so how can we make it suportable for both iOS 5 and iOS6

    • This code will always return a unique value, even when called repeatedly on the same device (and same OS).

    • John is absolutely correct. This code returns a globally unique value every time it is called. It is not the same as the (now deprecated) device identifier that was unique to a particular device but always the same for that device.

      That said, the code I posted also works on iOS6 and returns the same value that NSUUID would have returned if you had called it instead, so if you need to support iOS5 and above there is no reason to implement OS or class detection to select which method to use to generate the ID, you can simply use the CFUUIDRef solution for both.

Comments are closed.