我对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填充用户对象的团队属性。
我看了很多帖子,但是我尝试的都没有,这不是一个常见的用例吗?
有谁知道如何做到这一点,非常感谢帮助!
感谢。
答案 0 :(得分:17)
您需要向包含相关User
的{{1}}实体添加一个瞬态属性。这需要添加到您的teamId
。
然后,您需要为userMapping
添加关系定义:
userMapping
这为RestKit提供了建立连接所需的信息,并指示它将连接作为映射操作的一部分。