这是我的实体
- HomeArticle
identifier
article (relationship)
- Article
identifier
title
subtitle
text
home (relationship)
我有一个看起来像这样的有效负载:
[
{
"id": "1",
"title": "A Nice Simple One",
"subtitle": "Subtitle",
"text": "text text text"
},
{
"id": "2",
"title": "A Nice Simple Two",
"subtitle": "London",
"text": "text text text"
}
]
我正在尝试填充HomeArticle并同时创建关系,例如:
RKObjectManager* objectManager = [RKObjectManager sharedManager];
NSString *pathString = @"/get_news/";
[objectManager loadObjectsAtResourcePath:pathString usingBlock:^(RKObjectLoader *loader) {
loader.delegate = self;
loader.objectMapping = [self myHomeArticleMapping];
loader.onDidLoadObject = ^(id object) {
...
};
}];
- (RKManagedObjectMapping *) myHomeArticleMapping{
if(_homeArticleMapping == nil){
_homeArticleMapping = [RKManagedObjectMapping mappingForClass:[HomeArticle class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
[_homeArticleMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[_homeArticleMapping mapRelationship:@"article" withMapping:[self myArticleMapping]];
[_homeArticleMapping connectRelationship:@"article" withObjectForPrimaryKeyAttribute:@"identifier"];
}
}
- (RKManagedObjectMapping *) myArticleMapping{
if(_articleMapping == nil){
_articleMapping = [RKManagedObjectMapping mappingForClass:[Article class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
[_articleMapping mapKeyPath:@"id" toAttribute:@"identifier"];
[_articleMapping mapKeyPath:@"title" toAttribute:@"title"];
[_articleMapping mapKeyPath:@"subtitle" toAttribute:@"subtitle"];
[_articleMapping mapKeyPath:@"text" toAttribute:@"text"];
}
}
“HomeArticle”的标识符已填充,但未创建关系。你知道我怎么能做到这一点吗?我正在处理的项目有点复杂,但我简化了它以使其更清晰。
解决方法
好的,我设法完成这项工作的唯一方法是重新处理方法中的有效负载:
- (void)objectLoader:(RKObjectLoader*)loader willMapData:(inout id *)mappableData
我基本上从有效负载数组中创建了一个字典,将 id 作为键:
- (void)objectLoader:(RKObjectLoader*)loader willMapData:(inout id *)mappableData {
NSMutableArray *newsArray = [NSMutableArray arrayWithArray:(NSArray *)*mappableData];
NSMutableDictionary *newData = [[NSMutableDictionary alloc] init];
int elementNumber = [newsArray count];
for(int i = 0 ; i < elementNumber ; i++){
NSMutableDictionary *news = [NSMutableDictionary dictionaryWithDictionary:[newsArray objectAtIndex:i]];
[newData setObject:news forKey:[news objectForKey:@"id"]];
}
*mappableData = newData;
}
然后我改变了“HomeArticle”的映射,如下所示:
if(_homeArticleMapping == nil){
_homeArticleMapping = [RKManagedObjectMapping mappingForClass:[HomeArticle class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
_homeArticleMapping.forceCollectionMapping = YES;
[_homeArticleMapping mapKeyOfNestedDictionaryToAttribute:@"identifier"];
_homeArticleMapping.primaryKeyAttribute = @"identifier";
[_homeArticleMapping mapKeyPath:@"(identifier)"
toRelationship:@"article"
withMapping:[self myArticleMapping]];
}
它有效,但我真的不喜欢它。