开发者

Core Data - How to validate the uniqueness of an attribute within the scope of

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 a开发者_StackOverflow中文版nd 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!


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜