views:

348

answers:

1

The CoreData documentation says "You can sometimes benefit from creating your own unique ID (UUID) property which can be defined and set for newly inserted objects. This allows you to efficiently locate specific objects using predicates (though before a save operation new objects can be found only in their original context)."

What should be used for this type?

A managed object's objectID is usually 'NSManagedObjectID' type but the DataModel wizard tool via XCode that allows you to set the type for a given attribute only has the basic allowed types in addition to 'Undefined', Binary Data, & Transformable.

If I wanted to have an attribute that serves as a secondary id for an object (in addition to it's standard ObjectID), do you store it as an NSString or would you custom modify the object model to hold NSManagedObjectID?

(for iPhone app/CoreData development)

+1  A: 

An NSString or integer attribute are logical choices, though you could use a transformable attribute to store anything you wanted (that could be appropriately serialized, of course). An incrementing integer is probably good enough for many uses, but each use case is different. Many algorithms exist on the net for generating string or byte-array UUIDs (start with Google). An NSString UUID is quite easy:

+(NSString*)UUIDString {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [NSMakeCollectable(string) autorelease];
}

for an array of bytes, look at CFUUIDGetUUIDBytes().

Before you go this route, think long and hard about whether it is necessary. Folks coming from a SQL point of view "want" their ids, but Core Data is not about relational databases. It's an object graph management framework that just happens to use SQLite as one backing implementation. If you're trying to do SQL-like things in Core Data, you're going to be fighting the framework. There's often a way around needing a separate id property in proper usage of the Core Data framework.

Barry Wark
The last line should be `return [NSMakeCollectable(string) autorelease];` for correct memory management in both GC and retain/release modes.
Jim Correia