iOS Restkit如何在映射中关联实体

时间:2013-04-11 04:06:43

标签: ios objective-c mapping restkit relationship

我有2个实体:文章和类别。

//Article mapping
RKManagedObjectMapping *categoryMapping = [RKManagedObjectMapping mappingForClass:[Category class] inManagedObjectStore: objectManager.objectStore];
categoryMapping.primaryKeyAttribute = @"categoryId";
[categoryMapping mapKeyPathsToAttributes:
 @"CategoryId",@"categoryId",
 @"CategoryName",@"categoryName",
 nil];

//Category mapping
RKManagedObjectMapping *articleMapping = [RKManagedObjectMapping mappingForClass:[Article class] inManagedObjectStore: objectManager.objectStore];
articleMapping.primaryKeyAttribute = @"articleId";
[articleMapping mapKeyPathsToAttributes:
 @"ArticleId",@"articleId",
 @"ArticleName",@"articleName",
 @"ArticleText",@"articleText",
 @"CategoryId",@"categoryId",
 nil];

//relationship mapping
[categoryMapping mapRelationship:@"articles" withMapping:articleMapping];
[articleMapping mapRelationship:@"category" withMapping:categoryMapping];
[articleMapping connectRelationship:@"category" withObjectForPrimaryKeyAttribute:@"categoryId"];

//set mapping
[objectManager.mappingProvider setMapping:articleMapping forKeyPath:@"article"];
[objectManager.mappingProvider setMapping:categoryMapping forKeyPath:@"category"];

然后我想知道文章的类别,但它等于null:

   Article* article = [[Article allObjects] objectAtIndex:0];
   //article.category == nil

article.categoryId和category.categoryId相等。

为什么地图关系不起作用?

1 个答案:

答案 0 :(得分:0)

以这种方式尝试关系映射

[categoryMapping mapKeyPath:@"articles" toRelationship:@"articles" withMapping:articleMapping];  
[articleMapping mapKeyPath:@"category" toRelationship:@"category" withMapping:categoryMapping];  

这对我来说非常合适。我在我的两个项目中使用过它。