2

我有像这样的 REST 服务方法

/GetOfficeDocument?officeId=259

它返回一个文档数组。应用程序中的文档是一个与办公室有关系的 NSManagedObject 对象。如何将officeId参数映射到office我的关系Document

我知道我应该覆盖objectLoader:willMapData:,但我不知道我应该在这个方法中具体做什么。文档没用。

UPD。服务器的响应如下所示:

[{"AddedDate":"\/Date(1261484400000+0400)\/","Title":"Some text","Uri":"\/Document\/News\/851"}]

如您所见,officeId不包含在响应中,仅包含在 URL 中。我可以在objectLoader:willMapData:使用中提取它

[[[loader URL] queryParameters] objectForKey:@"officeId"]

但接下来我应该把它放在哪里?可映射数据参数是一个可变数组,我应该在那里放置什么?不知道。

4

2 回答 2

1

您可以尝试OfficeId在响应中返回的每个文档项中注入值,如下所示:

- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout __autoreleasing id *)mappableData
{
    NSString *officeId = [[[loader URL] queryParameters] objectForKey:@"officeId"];

    NSMutableArray *newMappableData = [[NSMutableArray alloc] initWithCapacity:[*mappableData count]];

    for (NSDictionary *documentDict in *mappableData)
    {
        NSMutableDictionary = newDocumentDict = [documentDict mutableCopy];
        [newDocumentDict setObject:officeId forKey:@"OfficeId"];
        [newMappableData addObject:newDocumentDict];
    }

    *mappableData = newMappableData;
}

Document并在映射中使用类似于以下内容的内容:

[documentMapping mapAttributes:@"AddedDate", @"Title", @"Uri", @"OfficeId", nil];
[documentMapping mapKeyPath:@"" toRelationship:@"office" withMapping:officeMapping];
[documentMapping connectRelationship:@"office" withObjectForPrimaryKeyAttribute:@"OfficeId"];
于 2012-08-17T13:48:07.893 回答
0

我通常添加RKObjectMapping到 managedObject 类

将此添加到您的 Document.h

  + (RKObjectMapping *)objectMapping;

将此方法添加到您的 Document.m

+ (RKObjectMapping *)objectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[self class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
     mapping.primaryKeyAttribute = @"word";
    [mapping mapKeyPath:@"word" toAttribute:@"word"];
    [mapping mapKeyPath:@"min_lesson" toAttribute:@"minLesson"];

}

当然,您应该更改 Document 对象属性的关键路径。每对都是服务器上响应的键的名称,它对应于 managedObject 上的 keyPath。

然后,当您初始化时,objectManager您可以为您拥有的每个 managedObject 设置映射。

 RKManagedObjectStore *store = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil delegate:self];
objectManager.objectStore = store;

 //set the mapping object from your Document class
[objectManager.mappingProvider setMapping:[SRLetter objectMapping] forKeyPath:@"Document"];

你可以在这里找到一个很棒的教程——RestKit 教程。在文章的中间,您将找到有关映射的数据。

于 2012-08-17T13:33:20.503 回答