Making UUID’s in Cocoa
If you haven’t heard of Universally Unique Identifiers or (UUIDs), they are a way to make a unique identifier for anything (possibly your database entries) from different locations without having to use a central server to create unique identifiers. As an example, you might want to create a unique identifier of your user inside your Cocoa app that will never clash with any other user’s unique ID. You could create your own server and write a script that would generate a unique ID for each client, but this is a centralized approach and requires a network connection, is slower, and involves processing time on your server. Instead you can use UUID’s, which are created on the client machine.
To do this in Cocoa is fairly easy. We just need to drop down to the Carbon API’s, which can be difficult for beginners. Here’s how:
1 2 3 4 5 | CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); CFStringRef strRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); NSString *uuidString = [NSString stringWithString:(NSString*)strRef]; CFRelease(strRef); CFRelease(uuidRef); |
Very simply, this creates a UUID, turns it into a string, and turns that Core Foundation string into an NSString. It then releases the memory of those two carbon objects. You will note that we just cast strRef as an NSString. This is toll-free bridging between CF and Cocoa going to work for you. If you have any questions or comments please feel free to comment below.
-
Oliver Beattie
-
Preston



