1

How do we get unique IDs in Objective C. I want to create a unique ID for my session & then generate a ID each time a server call happens. Each time this ID should be unique.

I tried using CFUUID class which gives us a huge unique ID (4FE9D00C-531E-45E8-B10E-11968ACC36E9). I want a unique ID of smaller size.

Any clue?

Abhinav
  • 37,684
  • 43
  • 191
  • 309

3 Answers3

6

A guid (by shear combinations) generates a unique id. If it's less characters you want then one option is to base64encode the guid. That allows for 64 possibilities per char instead of 16 (0-9, A-F)

This:

540c2d5f-a9ab-4414-bd36-9999f5388773

Becomes:

Xy0MVKupFES9NpmZ9TiHcw

For example: (C# though) http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx

Here's a SO post on objective-c encode/decode (look @ Mike Ho post):

How do I do base64 encoding on iphone-sdk?

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99
0

This was my question too, and I liked the answer, but I would like to let here a code done, and I know this is old, but maybe it can help someone:

// DataWithLength is a byte size of UUID. So 32 bytes = 256 bits string
- (NSString*)generateSecureUUID {

    NSMutableData *data = [NSMutableData dataWithLength:32];

    int result = SecRandomCopyBytes(NULL, 32, data.mutableBytes);

    NSAssert(result == 0, @"Error generating random bytes: %d", errno);

    NSString *base64EncodedData = [data base64EncodedStringWithOptions:0];

    return base64EncodedData;
}
J. Lopes
  • 1,336
  • 16
  • 27
0

you may try one of the following

1-

CFUUIDRef udidCFUUIDRef = CFUUIDCreate(NULL);
    NSString *UUIDString_token_name = (NSString *) CFBridgingRelease(CFUUIDCreateString(NULL, udidCFUUIDRef));

2-

NSString *UUIDString = [[NSUUID UUID] UUIDString];
Amr Angry
  • 3,711
  • 1
  • 45
  • 37