2013-09-21 72 views
8

当JSON响应仅包含主键而不是完全嵌套的数组来创建新对象时,我在映射关系时遇到问题。使用主键的RestKit关系映射

我有2个类 - 商店和项目,正如你所期望的商店 - >项目有一对多的关系。

我有一个商店(和项目)的本地核心数据存储,每个都有一个主键。然后,我希望下载一个物品列表作为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]; 
} 

编辑: 韦恩,我有这在应用程序代理相关的地方,但得到的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'' 

有什么我错过了?

回答

5

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

配置使用外键映射的关系:

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

然后使用addConnection:将其添加到您的映射。

+0

谢谢@Wain。这段代码是在App Delegate还是View Controller? Andy – Andy

+0

将它添加到'itemMapping'中,您之前曾尝试添加关系映射(但是对于嵌套项目)。 – Wain

+0

我收到一个异常 - 请参阅编辑。这是因为我没有创建项目的瞬态属性?如果是这样如何?安迪 – Andy