2012-09-28

Generate a UUID in Objective-C (iOS)

I am surprised to find that even by 2012 Apple has yet to include an object type for UUID. Nor do they provide an easy way to generate a UUID. Java does both.

The blog post Creating a GUID or UUID in Objective-C by Don McCaughey provides source code for a nice method to wrap Apple's clumsy UUID feature in Core Foundation. Unfortunately his 2010 code is not working for me Xcode 4.4.1, apparently because of ARC.

Error:
Cast of C pointer type 'CFStringRef' (aka 'const struct _CFString *') to Objective-C pointer type 'NSString *' requires a bridged cast

Two fix-its offered. I chose this one:
Use CFBridgingRelease call to transfer ownership of a +1 'CFStringRef' (aka 'const struct _CFString *' into ARC

And I deleted his call to autorelease.

Here is my revision to Mr. McCaughey’s code. My revision seems to be working. But is memory managed correctly? I am still too new to Objective-C and C to grasp the nuance of bridging OOP and POC (Plain Old C). Please post corrections or criticism.


//=================
    // Return a new UUID string. Built for ARC in iOS 4 and later.
- (NSString *)generateUuidString
{
        // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    
        // create a new CFStringRef.
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
        // release the UUID
    CFRelease(uuid);
    
    return uuidString;
}
//=================

StackOverflow.com has a thread on this topic.

No comments:

Post a Comment