如何强制RESTkit映射始终​​更新响应NSManagedObject而不在JSON正文中使用唯一ID

时间:2014-04-17 17:25:42

标签: json core-data restkit

我在响应JSON正文中没有任何特定的ID(我无法更改正文)。这就是为什么我不能使用

RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:....
mapping.identificationAttributes = @[@"specificId"];

是否可以配置映射,使得没有新的NSManagedObject被创建,但是如果存在这样的对象,则总是更新前一个NSManagedObject?

我想从单个响应对象(特定类)获取ui update的数据。是的我可以在收到新响应之前删除之前的响应实例,但此问题中所需的方法更清晰,我不需要将引用/ id保留给响应实体。

我正在阅读documentation for RKManagedObjectRequestOperation,但尚不清楚Restkit是否支持这种方法。

感谢您的评论。

1 个答案:

答案 0 :(得分:0)

我做了一个不被接受的黑客但是它有效:我在每个特殊的"单身"中使用了一个特殊的属性。 NSManagedObject的子类:例如 unique 我用于在班级上进行识别:

在RKManagedObjectMappingOperationDataSource中,修改了条件以允许传递具有特殊唯一属性的实体:

// If we have found the entity identification attributes, try to find an existing instance to update
if ([entityIdentifierAttributes count] || [self.managedObjectCache isUniqueEntityClass:entity])...

RKFetchRequestManagedObjectCache RKInMemoryManagedObjectCache 中定义了新方法:

- (BOOL) isUniqueEntityClass:(NSEntityDescription*)entity {

    __block BOOL isUniqueEntityClass = NO;

    [[[entity attributesByName] allKeys] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        isUniqueEntityClass = [obj isEqualToString:@"unique"];
        if(isUniqueEntityClass) {
            *stop = YES;
            return;
        }
    }];

    return isUniqueEntityClass;
}

方法

- (NSSet *)managedObjectsWithEntity:(NSEntityDescription *)entity
                    attributeValues:(NSDictionary *)attributeValues
             inManagedObjectContext:(NSManagedObjectContext *)managedObjectContext...

isUniqueEntityClass 决定是否应该使用基于 attributeValues 的谓词来获取实体或直接获取没有谓词的实体。