唯一性约束功能要求ios部署目标9.0或更高 - 核心数据

时间:2015-10-13 10:27:01

标签: ios core-data xcode7

IOS 9有一个很有用的功能,您可以在属性上添加唯一约束。 IOS 9 unique constraints

但是我想向上支持IOS 8,除非我将部署目标设置为9,否则无法编译。

有没有办法可以创建两个数据模型,并在编译器指令中使用数据模型 A IOS 8 和数据模型 B IOS 9 以及?

-----更新--------------------

在我用来手动添加唯一约束的代码下面

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CL" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        NSArray *entities = [_managedObjectModel entities];
        NSEntityDescription *entity = [entities firstObject];
        NSArray *properties = @[@"serverFileId"];
        [entity setUniquenessConstraints:@[properties]];
    }
    return _managedObjectModel;
}

1 个答案:

答案 0 :(得分:1)

相当有趣的问题,瑞恩。我想到的唯一解决方案是:

  • 您创建了一个符合iOS8 + iOS9标准的模型(没有唯一性 约束)。
  • 使用
  • 保护持久性商店协调员创建代码的某些部分

if #available(iOS 9.0, *) { // add uniqueness constraints here }

  • 您可以像编辑方式一样在受保护的范围内添加唯一性约束 here

<强>更新 我一直在寻找一种方法,以编程方式将唯一性约束应用于属性,最终得到了一个CoreData.NSEntityDescription类定义。这是一段理想的代码:

/* Returns/sets uniqueness constraints for the entity. A uniqueness constraint is a set of one or more attributes whose value must be unique over the set of instances of that entity.
    Returns/sets an array of arrays, each of which contains one or more NSAttributeDescription or NSString instances (strings must be the names of attributes on the entity) on which the constraint is registered. 
    This value forms part of the entity's version hash. Stores which do not support uniqueness constraints should refuse to initialize when given a model containing such constraints.
    Discussion: uniqueness constraint violations can be computationally expensive to handle. It is highly suggested that there be only one uniqueness constraint per entity hierarchy,
    although subentites may extend a sueprentity's constraint.
*/

@available(iOS 9.0, *)
public var uniquenessConstraints: [[AnyObject]]