views:

77

answers:

2

Is it possible to make a Core Data attribute unique, i.e. no two MyEntity objects can have the same myAttribute?

I know how to enforce this programatically, but I'm hoping there's a way to do it using the graphical Data Model editor in xcode.

I'm using the iPhone 3.1.2 SDK.

+2  A: 

You could override the setMyAttribute method (using categories) and ensure uniqueness right there, although this may be expensive:

- (void)setMyAttribute:(id)value
{
   NSArray *objects = [self fetchObjectsWithMyValueEqualTo:value];
   if( [objects count] > 0 )  // ... throw some exception
   [self setValue:value forKey:@"myAttribute"];
}

If you want to make sure that every MyEntity instance has a distinct myAttribute value, you can use the objectID of the NSManagedObject objects for that matter.

Martin Cote
Thanks for the fast reply!"You could override the setMyAttribute"That's what I'm doing at the moment. Thankfully the dataset is small enough that getting a list of all the objects is not too expensive, although I was hoping a more elegant solution was possible."If you want to make sure that every MyEntity instance has a distinct myAttribute value..."That's exactly what I want to do, although I'm struggling to see how the object's ID can be used for this purpose. Is it possible to assign your own ID to each object somehow?
robinjam
@robinjam, I was more talking about the fact that you could plug the objectID value somewhere in "myAttribute" to ensure that every values are unique.
Martin Cote
@Martin Cote: Oh, I see what you mean now. However, the attribute in question is actually a user-supplied name so that would not be ideal for my purpose. The reason I want to keep them unique is that the user would have no way of telling two objects with the same name apart. See my answer for the solution I settled on in the end. Thanks for your input!
robinjam
A: 

I've decided to use the validate<key>:error: method to check if there is already a Managed Object with the specific value of <key>. An error is raised if this is the case.

For example:

- (BOOL)validateMyAttribute:(id *)value error:(NSError **)error {
    // Return NO if there is already an object with a myAtribute of value
}

Thanks to Martin Cote for his input.

robinjam