唯一的NSManagedObject属性

时间:2012-08-30 12:09:15

标签: ios core-data nsmanagedobject

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

例如,是否应使用willSavevalidateForInsert:validateForUpdate:托管对象方法来检查attributeUnique中输入的值是否为唯一?而且,到底是怎么回事?

1 个答案:

答案 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;
}