views:

32

answers:

1

Hi,

I would like to know how to implement a validation in Core Data. What I'd like to do is ensure that an attribute is unique within the scope of a related parent object. In other words, I'm wondering how to implement the validates_uniqueness_of :field, :scope => :parent paradigm (from rails / activerecord) in Core Data.

For example, suppose I create two models - one called Blog and one called Post. Each Post has an attribute called title. Different Blog objects can have Posts with identical titles, but how do I validate the uniqueness of a title within the scope of a Blog?

Thanks!

A: 

Walk the relationship to the parent and grab the set of posts. Then you can run a predicate against it to check for uniqueness like:

NSSet *set = [[self parent] posts];
NSSet *filtered = [set filteredSetWithPredicate:[NSPredicate preicateWithFormat:@"self != %@ and title == %@", self, [self title]]];
if ([filtered count] > 0) return NO;
return YES;
Marcus S. Zarra