Sometimes it could be quite useful to have a function that generates unique identifiers. Unfortunately iOS SDK doesn’t have method that simply returns identifier as a string. You should use CFUUIDCreate (returns Universally Unique Identifier (UUID) object) with a couple of other functions to get your string identifier.
+ (NSString *) generateUUID {
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef str = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
NSString *string = (NSString *) str;
NSMutableString *result = [NSMutableString stringWithString: string];
[string autorelease];
[result replaceOccurrencesOfString: @"-" withString: @"" options: NSLiteralSearch
range: NSMakeRange(0, [result length]) ];
return result;
}
This method uses CFUUIDCreate to create CFUUIDRef instance. Then CFUUIDRef is converted to CFStringRef. We use toll-free bridged cast to get NSString from CFUUIDRef. Finally we remove “-” symbols from the string. Result will look like this “12500-EAD349-4493EB2-408C91ED-9C0BF4″.
Discover more from mycodetips
Subscribe to get the latest posts sent to your email.