Question

Im making an application that gets 3 JSON from a Wordpress site, then it maps them in 3 different classes: Products, Locations and Categories, the Products and Categories mapping works just fine, but when Im mapping the Locations it gets mixed with the Products, and causes an error in both, heres my Location class:

@interface Location : NSObject

@property (nonatomic, retain) NSString * alias;
@property (nonatomic, retain) NSSet * street;
@property (nonatomic, retain) NSSet * number;
@property (nonatomic, retain) NSSet * state;
@property (nonatomic, retain) NSSet * city;
@property (nonatomic, retain) NSSet * zipcode;
@property (nonatomic, copy) NSSet * locationId;

@end

and here is the Products class:

@interface AllProducts : NSObject

@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSSet * locationId;
@property (nonatomic, copy) NSSet * productCategoryId;
@property (nonatomic, strong) NSMutableArray *prices;

@end

below is the mapping Im using:

//Products Mapping
    RKObjectMapping *productsMapping = [RKObjectMapping mappingForClass:[AllProducts class]];
    [productsMapping addAttributeMappingsFromDictionary:@{
                                                      @"title": @"name",
                                                      @"custom_fields.product_0_sucursal": @"locationId",
                                                      /*@"custom_fields.tipo_de_producto": @"productType",
                                                      @"custom_fields.product_0_price": @"price",
                                                      @"custom_fields.product_0_real_id": @"realId",
                                                      @"custom_fields.product_0_size": @"size",
                                                      @"custom_fields.product_0_modificador": @"mod",
                                                      @"custom_fields.product_0_temperatura": @"temp",*/
                                                      @"categories.id": @"productCategoryId"
                                                      }];

[productsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"custom_fields"
                                                                                toKeyPath:@"prices"
                                                                             withMapping:pricesMapping]];


RKResponseDescriptor *productsResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productsMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"posts" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:productsResponseDescriptor];

//Locations Mapping
RKObjectMapping *locationsMapping = [RKObjectMapping mappingForClass:[Location class]];
[locationsMapping addAttributeMappingsFromDictionary:@{
                                                       @"title": @"alias",
                                                       @"custom_fields.calle": @"street",
                                                       @"custom_fields.numero": @"number",
                                                       @"custom_fields.estado": @"state",
                                                       @"custom_fields.ciudad": @"city",
                                                       @"custom_fields.codigo_postal": @"zipcode",
                                                       @"custom_fields.locationid": @"locationId"
                                                       }];

RKResponseDescriptor *locationsResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:locationsMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"posts" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:locationsResponseDescriptor];

I have the mapping definitions in the AppDelegate, and the call of the objects is in the tableview controllers

For Locations:

RKObjectManager* objectManager = [RKObjectManager sharedManager];


NSDictionary *parameters;

parameters = @{
               @"json" : @"get_posts",
               @"post_type" : @"locations"
               };


[objectManager getObjectsAtPath:@"" parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
 {

     _locations = [mappingResult array];
     [[self tableView]reloadData];
 }
                        failure:^(RKObjectRequestOperation *operation, NSError *error){
                            [self handleFailure:operation withError:error];
                        }];

and for Products:

 //Getting all the products
RKObjectManager *objectManager = [RKObjectManager sharedManager];

//Mutable array that will contain the products when a category is selected
_productByCategory = [[NSMutableArray alloc] init];

NSDictionary *parameters;

http://localhost/?json=get_posts&post_type=products

parameters = @{
               @"json" : @"get_posts",
               @"post_type" : @"products"
               };

//Getting all the products and then selecting only the products that are in the category selected
[objectManager getObjectsAtPath:@"" parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
 {

     _products = [mappingResult array];
     NSArray *tempProducts = _products;
     //NSString *productToAdd;

     BOOL isDuplicate = NO;

     for(NSSet *currentProduct in tempProducts)
     {
         for(NSSet *product in _productByCategory)
         {
             if ([[currentProduct valueForKey:@"_name"] isEqualToString:[product valueForKey:@"_name"]]){
                 isDuplicate = YES;
                 break;
             }
         }

         if(!isDuplicate && [currentProduct valueForKey:@"_name"] != nil && [[currentProduct valueForKey:@"_productCategoryId" ] containsObject:category.categoryId] && [[currentProduct valueForKey:@"_locationid"] containsObject:location.locationId]){
             //productToAdd = [[NSString alloc] initWithFormat:@"%@", [currentProduct valueForKey:@"_name"]];
             [_productByCategory addObject:currentProduct];
         }
         /*if([[currentProduct valueForKey:@"_productCategoryId" ] containsObject:category.categoryId])
         {
             [_productByCategory addObject:currentProduct];
         }*/
     }
     [[self tableView]reloadData];
 }
failure:^(RKObjectRequestOperation *operation, NSError *error){
     [self handleFailure:operation withError:error];
 }];

//update view title
self.title = [category.categoryName lowercaseString];

and below are the JSON for both:

http://localhost/?json=get_posts&post_type=locations
{
"status": "ok",
"count": 2,
"count_total": 2,
"pages": 1,
"posts": [
    {
        "id": 263,
        "type": "locations",
        "slug": "sucursal-plaza-regia",
        "url": "http://localhost/?locations=sucursal-plaza-regia",
        "status": "publish",
        "title": "Sucursal Plaza Regia",
        "title_plain": "Sucursal Plaza Regia",
        "content": "",
        "excerpt": "",
        "date": "2014-03-25 15:44:29",
        "modified": "2014-03-25 15:44:29",
        "categories": [],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "arturocalvo",
            "name": "arturocalvo",
            "first_name": "",
            "last_name": "",
            "nickname": "arturocalvo",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "closed",
        "custom_fields": {
            "calle": [
                "Av. Eugenio Garza Sada"
            ],
            "numero": [
                "No. 3720 Local L-3"
            ],
            "estado": [
                "Nuevo Leon"
            ],
            "ciudad": [
                "Monterrey"
            ],
            "codigo_postal": [
                "64780"
            ],
            "locationid": [
                "3"
            ]
        }
    },
    {
        "id": 256,
        "type": "locations",
        "slug": "sucursal-plaza-404-2",
        "url": "http://localhost/?locations=sucursal-plaza-404-2",
        "status": "publish",
        "title": "Sucursal Plaza 404",
        "title_plain": "Sucursal Plaza 404",
        "content": "",
        "excerpt": "",
        "date": "2014-03-24 16:58:20",
        "modified": "2014-03-24 16:58:20",
        "categories": [],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "arturocalvo",
            "name": "arturocalvo",
            "first_name": "",
            "last_name": "",
            "nickname": "arturocalvo",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "closed",
        "custom_fields": {
            "calle": [
                "Av. Gomez Morin"
            ],
            "numero": [
                "404 Local A3-5"
            ],
            "estado": [
                "Nuevo Leon"
            ],
            "ciudad": [
                "San Pedro Garza Garcia"
            ],
            "codigo_postal": [
                "66220"
            ],
            "locationid": [
                "2"
            ]
        }
    }
],
"query": {
    "ignore_sticky_posts": true,
    "post_type": "locations"
}
}

{
"status": "ok",
"count": 5,
"count_total": 5,
"pages": 1,
"posts": [
    {
        "id": 267,
        "type": "products",
        "slug": "cafe-americano-3",
        "url": "http://localhost/?products=cafe-americano-3",
        "status": "publish",
        "title": "Cafe Americano",
        "title_plain": "Cafe Americano",
        "content": "",
        "excerpt": "",
        "date": "2014-03-25 16:55:58",
        "modified": "2014-03-25 16:55:58",
        "categories": [
            {
                "id": 1,
                "slug": "coffeebar",
                "title": "Coffee Bar",
                "description": "",
                "parent": 0,
                "post_count": 3
            }
        ],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "arturocalvo",
            "name": "arturocalvo",
            "first_name": "",
            "last_name": "",
            "nickname": "arturocalvo",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "closed",
        "custom_fields": {
            "tipo_de_producto": [
                "bebida"
            ],
            "tipo_de_bebida": [
                "cafe"
            ],
            "product_0_size": [
                "l"
            ],
            "product_0_price": [
                "30"
            ],
            "product_0_sucursal": [
                "2"
            ],
            "product_0_temperatura": [
                "caliente"
            ],
            "product_0_modificador": [
                "regular"
            ],
            "product_0_priceid": [
                "432"
            ],
            "product": [
                "1"
            ]
        }
    },
    {
        "id": 266,
        "type": "products",
        "slug": "cafe-americano-2",
        "url": "http://localhost/?products=cafe-americano-2",
        "status": "publish",
        "title": "Cafe Americano",
        "title_plain": "Cafe Americano",
        "content": "",
        "excerpt": "",
        "date": "2014-03-25 16:55:23",
        "modified": "2014-03-25 16:55:23",
        "categories": [
            {
                "id": 1,
                "slug": "coffeebar",
                "title": "Coffee Bar",
                "description": "",
                "parent": 0,
                "post_count": 3
            }
        ],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "arturocalvo",
            "name": "arturocalvo",
            "first_name": "",
            "last_name": "",
            "nickname": "arturocalvo",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "closed",
        "custom_fields": {
            "tipo_de_producto": [
                "bebida"
            ],
            "tipo_de_bebida": [
                "cafe"
            ],
            "product_0_size": [
                "s"
            ],
            "product_0_price": [
                "25"
            ],
            "product_0_sucursal": [
                "3"
            ],
            "product_0_temperatura": [
                "caliente"
            ],
            "product_0_modificador": [
                "regular"
            ],
            "product_0_priceid": [
                "438"
            ],
            "product": [
                "1"
            ]
        }
    }

The problem is that when I make the request for only products, it works fine, when i make the request for only locations it works fine too, but when the two are made, location tries to map to products class and products tries to map to location class, and I get an Error, can somebody help me to know what Im doing wrong?, thanks in advance

Was it helpful?

Solution

Because RestKit can't tell the difference between the responses because the path patterns and key paths of both descriptors are identical (all of the difference is in the URL query parameters and they aren't used by RestKit).

So, you either need to change the request URL (and change pathPattern:nil on the response descriptors). Or change the JSON (so you have a different key path). Or delete the response descriptors after each request and recreate only the appropriate one before a request. Or use 2 different object managers, each with only 1 response descriptor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top