Core Data unique attributes

后端 未结 7 1353
眼角桃花
眼角桃花 2020-12-02 10:01

Is it possible to make a Core Data attribute unique, i.e. no two MyEntity objects can have the same myAttribute?

I know how to enforce this programatically, but I\'m

7条回答
  •  爱一瞬间的悲伤
    2020-12-02 10:36

    From IOS 9 there is a new way to handle unique constraints.

    You define the unique attributes in the data model.

    You need to set a managed context merge policy "Merge policy singleton objects that define standard ways to handle conflicts during a save operation" NSErrorMergePolicy is the default,This policy causes a save to fail if there are any merge conflicts.

    - (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
        if (_managedObjectContext != nil) {
            return _managedObjectContext;
        }
    
        NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
        if (!coordinator) {
            return nil;
        }
      _managedObjectContext = [[NSManagedObjectContext alloc]    initWithConcurrencyType:NSMainQueueConcurrencyType];
      [_managedObjectContext setPersistentStoreCoordinator:coordinator];
      [_managedObjectContext setMergePolicy:NSOverwriteMergePolicy];
        return _managedObjectContext;
    }
    

    The various option are discussed at Apple Ducumentation Merge Policy

    It is answered nicely here Zachary Orr's Answer

    and he has kindly also created a blogpost and sample code.

    Sample Code

    Blog Post

    The most challenging part is to get the data Model attributes editable.The Secret is to left click and then right click, after you have clicked the + sign to add a constraint.

提交回复
热议问题