开发者

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

开发者 https://www.devze.com 2023-01-07 07:56 出处:网络
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 ho

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

精彩评论

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

关注公众号