使用RestKit进行外键关系映射

时间:2013-06-26 16:54:46

标签: ios json restkit restkit-0.20

我对RestKit完全不熟悉并且在某种程度上挣扎。

JSON:

{
    "teams": [
        {
            "id": 1,
            "name": "Team A"
        },
        {
            "id": 2,
            "name": "Team B"
        }
    ],
    "users": [
        {
            "id": 1,
            "name": "cameron",
            "teamId": 1
        },
        {
            "id": 2,
            "name": "paul",
            "teamId": 2
        }
    ]
}

CoreData:

@interface Team : NSManagedObject
@property (nonatomic, retain) NSNumber * teamId;
@property (nonatomic, retain) NSString * name;
@end




@interface User : NSManagedObject
@property (nonatomic, retain) NSNumber * userId;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Team * team;
@end

我的应用程序逻辑如下所示:

// team mapping
RKEntityMapping *teamMapping = [RKEntityMapping mappingForEntityForName:@"Team" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
teamMapping.identificationAttributes = @[@"teamId"];
[teamMapping addAttributeMappingsFromDictionary:@{
 @"id": @"teamId",
 @"name": @"name"
 }];


// Register our mappings with the provider
RKResponseDescriptor *teamResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:teamMapping
                                                                                   pathPattern:nil
                                                                                       keyPath:@"teams"
                                                                                   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self.objectManager addResponseDescriptor:teamResponseDescriptor];



// user mapping
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
userMapping.identificationAttributes = @[@"userId"];
[userMapping addAttributeMappingsFromDictionary:@{
 @"id": @"userId",
 @"name": @"name"
 }];


// Register our mappings with the provider
RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
                                                                                   pathPattern:nil
                                                                                       keyPath:@"users"
                                                                                   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self.objectManager addResponseDescriptor:userResponseDescriptor];

我无法为我的生活弄清楚如何让RestKit填充用户对象的团队属性。

我看了很多帖子,但是我尝试的都没有,这不是一个常见的用例吗?

有谁知道如何做到这一点,非常感谢帮助!

感谢。

1 个答案:

答案 0 :(得分:17)

您需要向包含相关User的{​​{1}}实体添加一个瞬态属性。这需要添加到您的teamId

然后,您需要为userMapping添加关系定义:

userMapping

这为RestKit提供了建立连接所需的信息,并指示它将连接作为映射操作的一部分。