与RestKit的外键关系映射
我对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来填充用户对象的团队属性。
我看了这么多的post,但没有我尝试的作品,这不是一个常见的用例?
有谁知道如何做到这一点,帮助将非常感激!
谢谢。
你需要添加一个瞬态属性到你的User
实体,持有相关的teamId
。 这需要添加到你的userMapping
。
然后,你需要添加一个关系定义到你的userMapping
:
[userMapping addConnectionForRelationship:@"team" connectedBy:@{ @"teamId": @"teamId" }];
这为RestKit提供了build立连接所需的信息,并指示它将连接作为映射操作的一部分。