将NSManagedObject
属性设为唯一的最佳方法是什么?
例如,是否应使用willSave
或validateForInsert:
或validateForUpdate:
托管对象方法来检查attributeUnique
中输入的值是否为唯一?而且,到底是怎么回事?
答案 0 :(得分:0)
我最后编写了NSManagedObject
类别方法,并使用了NSManagedObject
的验证方法:
- (BOOL)isValueUniqueForKey:(NSString *)key {
NSEntityDescription *entity = [NSEntityDescription entityForName:[self.entity name]
inManagedObjectContext:self.managedObjectContext];
id value = [self valueForKey:key];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ = %@", key, value];
fetchRequest.predicate = predicate;
NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest
error:&error];
if (count > 1) {
return NO;
}
return YES;
}