11

我对 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
        }
    ]
}

核心数据:

@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 填充用户对象的团队属性。

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

有谁知道如何做到这一点,帮助将不胜感激!

谢谢。

4

1 回答 1

17

您需要向User包含关联的实体添加一个瞬态属性teamId。这需要添加到您的userMapping.

然后,您需要将关系定义添加到您的userMapping

[userMapping addConnectionForRelationship:@"team" connectedBy:@{ @"teamId": @"teamId" }];

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

于 2013-06-27T18:46:58.523 回答