Core Data unique attributes

后端 未结 7 1347
眼角桃花
眼角桃花 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:40

    Every time i create on object I perform a class method that makes a new Entity only when another one does not exist.

    + (TZUser *)userWithUniqueUserId:(NSString *)uniqueUserId inManagedObjectContext:(NSManagedObjectContext *)context
    {
        TZUser *user = nil;
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
    
        request.entity = [NSEntityDescription entityForName:@"TZUser" inManagedObjectContext:context];
        request.predicate = [NSPredicate predicateWithFormat:@"objectId = %@", uniqueUserId];
        NSError *executeFetchError = nil;
        user = [[context executeFetchRequest:request error:&executeFetchError] lastObject];
    
        if (executeFetchError) {
             NSLog(@"[%@, %@] error looking up user with id: %i with error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [uniqueUserId intValue], [executeFetchError localizedDescription]);
        } else if (!user) {
            user = [NSEntityDescription insertNewObjectForEntityForName:@"TZUser" 
                                                 inManagedObjectContext:context];
        }
    
        return user;
    }
    

提交回复
热议问题