1

使NSManagedObject属性唯一的最佳方法是什么?

例如,是否应该使用willSavevalidateForInsert:validateForUpdate:托管对象方法来检查输入的值attributeUnique是否是唯一的?而且,究竟如何?

4

1 回答 1

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;
}
于 2012-09-14T11:08:28.110 回答