我有像这样的REST服务方法
/GetOfficeDocument?officeId=259
返回一个文档数组。应用程序中的文档是与办公室有关系的NSManagedObject对象。如何将officeId
param映射到office
的{{1}}关系?
我知道我应该覆盖Document
,但我不知道我应该在这个方法中做些什么。文档没用。
UPD。服务器的响应如下所示:
objectLoader:willMapData:
如您所见,[{"AddedDate":"\/Date(1261484400000+0400)\/","Title":"Some text","Uri":"\/Document\/News\/851"}]
未包含在回复中,仅包含在网址中。我可以使用
officeId
中提取它
objectLoader:willMapData:
但我应该把它放在哪里?可映射数据参数是一个可变数组,我应该放在那里?不知道。
答案 0 :(得分: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"];
答案 1 :(得分: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对象属性的关键路径。每一对都是服务器响应的密钥的名称,它在您的托管对象上对应keyPath。
然后,当您初始化objectManager
时,您可以为每个托管对象设置映射。
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 tutorial。在本文的中间,您将找到有关映射的数据。