RestKit:如何使用RKMappingOperation

时间:2013-12-12 12:14:39

标签: json restkit restkit-0.20

我有一个通过Web套接字检索的JSON结构,我想要应用于现有的托管对象。要修改的特定对象由JSON中的一个键标识。 JSON可能不包含所有属性,但我只想更新JSON中存在的属性(不会使其他属性无效)。

我在RestKit IRC频道上获得了一些使用RKMappingOperation的初始指针,但我现在仍然坚持实现。

首先我尝试了这个:

        RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:parsedObject destinationObject:nil mapping:[MyManagedObjectClass customMapping]];

由于我手头没有要更新的对象实例,我将nil传递给destinationObject,跳转映射器会根据提供的映射计算出来。

唉,执行映射后我从mappingOperation的mappingInfo中得到nil(但没有错误)。

        [mappingOperation performMapping:&localError];

        if (localError != nil) {
            NSLog(@"%@", [mappingOperation mappingInfo]); // outputs nil
        } else {
            NSLog(@"error: %@", localError); // no error
        }

所以我的预感是我确实需要获取我想要更新的托管对象实例并将其提供给映射操作,但我无法弄清楚如何。我尝试在托管对象上下文中使用existingObjectWithID,在我的JSON中传递ID,但没有运气。将其传递给映射操作时,我得到一个'null'错误。

我是否在正确的轨道上?我错过了什么?

编辑:在摆弄了一些之后,我意识到文档指定如果destinationObject设置为nil,则必须提供dataSource。所以这就是我接下来尝试的内容:

        RKManagedObjectMappingOperationDataSource *mappingDS = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:[[[RKObjectManager sharedManager ] managedObjectStore] mainQueueManagedObjectContext] cache:[[[RKObjectManager sharedManager] managedObjectStore] managedObjectCache]];
        mappingOperation.dataSource = mappingDS;

令人尴尬的是,我还把错误条件混淆了,这就是为什么我在前一次尝试时看不到错误(没有数据源)。现在看来映射操作成功执行了。如果实际情况会报告,并回答我自己的问题: - )

1 个答案:

答案 0 :(得分:3)

解决方案:

RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:parsedObject destinationObject:nil mapping:[MyManagedObjectClass customMapping]];

RKManagedObjectMappingOperationDataSource *mappingDS = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:[[[RKObjectManager sharedManager ] managedObjectStore] mainQueueManagedObjectContext] cache:[[[RKObjectManager sharedManager] managedObjectStore] managedObjectCache]];
mappingOperation.dataSource = mappingDS;

[mappingOperation performMapping:&localError];

    if (localError != nil) {
        NSLog(@"%@", [mappingOperation mappingInfo]);
    } else {
        NSLog(@"error: %@", localError);
    }