RestKit与主键的关系映射

时间:2013-09-21 16:17:35

标签: ios restkit restkit-0.20

当JSON响应只包含主键而不是完全嵌套的数组来创建新对象时,我无法映射关系。

我有2个课程 - 商店和项目,正如您所期望的那样,Shop-> Item具有一对多的关系。

我有一个商店(和商品)的本地核心数据存储,每个商店都有一个主键。然后我希望下载一个项目列表作为JSON并映射到核心数据实体,但只包括商店的主键,而不是所有商店详细信息作为嵌套数组 - 这将是巨大的网络流量浪费,因为我我正在下载500多个项目的详细信息。

以下是两个请求中的JSON:

/商店

{
    "id" : 1,
    "shop" : "Shop A",
    "city" : "New York"
},
{
    "id" : 2,
    "shop" : "Shop B",
    "city" : "London"
},
...

/项

{
    "id" : 1,
    "name" : "Shoes",
    "manufacturer" : "Vans",
    "shopId" : 1
},
{
    "id" : 2,
    "name" : "T-shirt",
    "manufacturer" : "Animal",
    "shopId" : 2
},
{
    "id" : 3,
    "name" : "Scarf",
    "manufacturer" : "Ted Baker",
    "shopId" : 1
},
{
    "id" : 4,
    "name" : "Sunglasses",
    "manufacturer" : "Ray-Ban",
    "shopId" : 3
},
...

这是我目前的代码。

AppDelegate.m

...

NSURL *baseURL = [NSURL URLWithString:@"http://localhost/company/API"];
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];

[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

[objectManager.HTTPClient setDefaultHeader:@"Accept" value:@"application/json"];

NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;

// Shop Mapping

RKEntityMapping *shopMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([Shop class])
                                                       inManagedObjectStore:objectManager.managedObjectStore];
NSDictionary *shopMappingAttributes = [NSDictionary dictionaryWithObjectsAndKeys:@"objectId",@"id",@"name",@"shop",@"city",@"city",nil];
shopMapping.identificationAttributes = @[@"objectId"];
[shopMapping addAttributeMappingsFromDictionary:shopMappingAttributes];
[objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:shopMapping
                                                                             pathPattern:@"/shops"
                                                                                 keyPath:nil
                                                                             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];


// Item Mapping

RKEntityMapping *itemMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([Item class])
                                                       inManagedObjectStore:objectManager.managedObjectStore];
NSDictionary *itemMappingAttributes = [NSDictionary dictionaryWithObjectsAndKeys:@"objectId",@"id",@"name", @"name",@"manufacturer",@"manufacturer",nil];
itemMapping.identificationAttributes = @[@"objectId"];
[itemMapping addAttributeMappingsFromDictionary:itemMappingAttributes];

// Define the relationship mapping

[objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:itemMapping
                                                                             pathPattern:@"/items"
                                                                                 keyPath:nil
                                                                             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];

...

ItemsTableViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    // Update Shops
    [[RKObjectManager sharedManager] getObjectsAtPath:@"/shops"
                                       parameters:nil
                                          success:nil
                                          failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                              NSLog(@"Error: %@",error);
                                          }];

    // Update/Get Items
    NSDictionary *parameters = @{
                             @"username": self.username,
                             @"password": self.password,
                             @"API_key": @"abc123",
                             };

    NSMutableURLRequest *request = [[RKObjectManager sharedManager] requestWithObject:nil
                                                                           method:RKRequestMethodPOST
                                                                             path:@"/items"
                                                                       parameters:parameters];

    RKManagedObjectRequestOperation *operation = [[RKObjectManager sharedManager] managedObjectRequestOperationWithRequest:request managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext
                                                                  success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                                                      Item *item = [mappingResult firstObject];
                                                                      NSLog(@"Mapped the Item: %@", item);
                                                                  } failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                                      NSLog(@"Error: %@",error);
                                                                  }];
    NSOperationQueue *operationQueue = [NSOperationQueue new];
    [operationQueue addOperation:operation];
}

修改 的 Wain,我在app委托中的相关位置有这个但是获得NSException

NSEntityDescription *itemEntity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext];
NSRelationshipDescription *shopRelationship = [itemEntity relationshipsByName][@"shop"];
RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:shopRelationship attributes:@{ @"shopId": @"objectId" }];
[itemMapping addConnection:connection];

NSException

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Item''

我错过了什么?

1 个答案:

答案 0 :(得分:5)

您需要为项目添加一个瞬态属性(称为shopId)和相关的映射。

使用外键映射配置关系:

NSEntityDescription *itemEntity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:managedObjectContext];
NSRelationshipDescription *shopRelationship = [itemEntity relationshipsByName][@"shop"];
RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:shopRelationship attributes:@{ @"shopId": @"id" }];

然后使用addConnection:将其添加到您的地图中。