Mapping top level items and embedded arrays with RestKit - ios

Given the following JSON structure:
{
"foo": {
"anno": "blah",
"domini": null,
"locations": [
{
"data": {
"lat": null,
"lon": null
},
"data": {
"lat": null,
"lon": null
}
}
]
}
}
How do I set up RestKit mappings for this scenario? I though I had it, but I'm unable to map the top-level foo items anno, and domini. I can successfully map locations on its own, but not in coordination with foo.
I've done this successfully in the past, but something is escaping me now.
Foo.h
#interface Foo : NSObject
#property (nonatomic, strong) NSString *anno;
#property (nonatomic, strong) NSString *domini;
#end
Location.h
#interface LocationData : NSObject
#property NSString *lat;
#property NSString *lon;
#end
Controller.m
RKObjectMapping *fooMapping = [RKObjectMapping mappingForClass:[Foo class]];
[fooMapping addAttributeMappingsFromArray:#[#"anno", #"domini"]];
RKObjectMapping *locationMapping = [RKObjectMapping mappingForClass:[Location class]];
[locationMapping addAttributeMappingsFromArray:#[#"lat",#"lon"]];
[fooMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"location" toKeyPath:#"location" withMapping: locationMapping]];
RKResponseDescriptor *fooReponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:dataMapping method:RKRequestMethodGET pathPattern:#"foo" keyPath:#"foo" statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKResponseDescriptor *locationResponseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:locationdMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#"foo.location"
statusCodes:[NSIndexSet indexSetWithIndex:200]];
I think that's all of the important stuff. Hopefully in my zeal to pare down how much text I was posting I didn't leave anything important out.
EDIT 2015-03-29
- (void)loadChildren {
NSDictionary *queryParams = #{#"sort" : #"new"};
[[RKObjectManager sharedManager] getObjectsAtPath:redditPath
parameters:queryParams
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
_children = mappingResult.array;
[self.tableView reloadData];
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"You mean YOU'RE the lunatic who's responsible for almost destroying my ship? : %#", error);
}];
}
redditpath is set earlier using...
redditPath = [NSString stringWithFormat:#"/r/%#/new.json", subRedditToLoad];
Where subRedditToLoad is, in this case, aww.

In your XCDataModel Take an Entity with named Foo.
Set Property of anno and vomini.
Also Create another Entity Location.
Set a property named data with type Transformable.
Add Relationship at Foo for Location entity put it many relationship.
Call mapping for Foo Like:
[mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"foo" toKeyPath:#"Foo" withMapping:[Location objectMappingForLocation:Enum]]];

Related

Restkit - Relationship mapping not working

I'm experiencing Restkit, using the version 0.25.0. I followed exactly what the documentation says for the relationship mapping, but for some reasons, I have an empty mapping result !
But when I remove the relationship object (data), I have a mapping result !!! But of course, the mapping result doesn't contain the data I need, the one I added as relationship.
I followed the example they have in this link :
https://github.com/RestKit/RestKit/wiki/Object-mapping#relationships
When I print the JSON with the debugger, here's the output :
{
"status": "success",
"data": {
"id": 11,
"provider": "email",
"uid": "riri#gmail.com",
"name": null,
"nickname": null,
"image": null,
"email": "riri#gmail.com",
"country": "United States",
"city": "Milan, Metropolitan City of Milan, Italy",
"gender": "m",
"birthday": "2015-06-25"
}
}
Here's the code how I make the request :
RKObjectManager *manager = [RKObjectManager sharedManager];
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
RKObjectMapping *jsonResponseMapping = [JSONResponse mappingObject];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:jsonResponseMapping
method:RKRequestMethodAny
pathPattern:#"/auth/sign_in"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[manager addResponseDescriptor:responseDescriptor];
NSDictionary *parameters = #{
#"email": user.email,
#"password": user.password
};
[manager postObject:user path:#"/auth/sign_in" parameters:parameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSDictionary *headerFields = operation.HTTPRequestOperation.response.allHeaderFields;
[self updateUserInfoForResponse:[mappingResult firstObject] headerFields:headerFields];
if (successBlock) {
successBlock([mappingResult firstObject]);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
if (failureBlock) {
failureBlock(error.userInfo[RKObjectMapperErrorObjectsKey][0], error);
}
}];
.m of JSONResponse class:
+ (RKObjectMapping *)mappingObject {
RKObjectMapping *jsonResponseMapping = [RKObjectMapping mappingForClass:[JSONResponse class]];
[jsonResponseMapping addAttributeMappingsFromDictionary:#{
#"status": #"status",
#"errors": #"errors",
}];
RKRelationshipMapping *userRelationShip = [RKRelationshipMapping relationshipMappingFromKeyPath:#"data" toKeyPath:#"data" withMapping:[User mappingObject]];
[jsonResponseMapping addPropertyMapping:userRelationShip];
return jsonResponseMapping;
}
.h Of JSONResponse class :
#import <RestKit/Restkit.h>
#import <Foundation/Foundation.h>
#import "User.h"
#interface JSONResponse : NSObject
#property (nonatomic, copy) NSString *status;
#property (nonatomic) User *data;
#property (nonatomic, copy) NSDictionary *errors;
/**
#function mappingObject
#return RKObjectMapping mapping for the json response
*/
+ (RKObjectMapping *)mappingObject;
#end
.m of User class
#import "User.h"
#implementation User
+ (RKObjectMapping *)mappingObject {
RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]];
[userMapping addAttributeMappingsFromDictionary:#{
#"email": #"email",
#"password": #"password",
#"gender": #"gender",
#"birthday": #"dateOfBirth",
#"city": #"city",
#"country": #"country"
}];
return userMapping;
}
#end
.h of User class
#class RKObjectMapping;
#interface User : NSObject
#property (nonatomic, copy) NSString *email;
#property (nonatomic, copy) NSString *password;
#property (nonatomic, copy) NSString *gender;
#property (nonatomic, copy) NSString *dateOfBirth;
#property (nonatomic, copy) NSString *city;
#property (nonatomic, copy) NSString *country;
/**
#function mappingObject
#return RKObjectMapping mapping object for user
*/
+ (RKObjectMapping *)mappingObject;
#end
Is there anything wrong in my models objects ? The relationship is set properly right ? I do have the data property in the JSONResponse, and the JSON contains correctly the keyPath data.
So I'm pretty confused why I have results when I remove my relationship, and why the mapping result is empty when I have the relationship. It's even doesn't go in the failureCallback, the operation is successful, the result is empty.
Any ideas ??
EDIT :
Here's the logs :
2015-09-15 07:27:50.649 testRestkit[53698:3448725] D restkit.object_mapping:RKPropertyInspector.m:154 Cached property inspection for Class 'JSONResponse': {
data = "<RKPropertyInspectorPropertyInfo: 0x7facf2c5fa00>";
status = "<RKPropertyInspectorPropertyInfo: 0x7facf2c5f7d0>";
}
2015-09-15 07:27:50.650 testRestkit[53698:3448725] D restkit.object_mapping:RKPropertyInspector.m:154 Cached property inspection for Class 'User': {
email = "<RKPropertyInspectorPropertyInfo: 0x7facf2c60680>";
}
2015-09-15 07:27:50.820 testRestkit[53698:3448725] I restkit.network:RKObjectRequestOperation.m:150 POST 'http://sandrotchikovani.com/test.php'
2015-09-15 07:27:51.236 testRestkit[53698:3448938] D restkit.object_mapping:RKMapperOperation.m:407 Executing mapping operation for representation: {
data = {
email = "lol#gmail.com";
};
status = success;
}
and targetObject: <User: 0x7facf2c05820>
2015-09-15 07:27:51.237 testRestkit[53698:3448938] T restkit.object_mapping:RKMapperOperation.m:350 Examining keyPath '<null>' for mappable content...
2015-09-15 07:27:51.237 testRestkit[53698:3448938] D restkit.object_mapping:RKMapperOperation.m:330 Found mappable data at keyPath '<null>': {
data = {
email = "lol#gmail.com";
};
status = success;
}
2015-09-15 07:27:51.237 testRestkit[53698:3448938] D restkit.object_mapping:RKMapperOperation.m:433 Finished performing object mapping. Results: {
}
Isn't weird that in the log, it says and targetObject: <User: 0x7facf2c05820> ? When I remove the relationship, there is a mapping result and the targetObject, displays "null".
You are calling postObject:..., and when you do that RestKit will map back to the original object. In this case that's a user and that's why you're seeing the log and targetObject: <User: 0x7facf2c05820>.
The easiest thing for you to do is to setup your JSONResponse so that you post it and receive the response into it. It already has the required user so a simple change to the request descriptor to pull out the user fields should be enough.
Alternatively there are a bunch of other questions about mapping to a different object after posting.

RESTKit: Objects are losing relationships

JSON data received:
{
"meeting": [{
"meetingId": 506,
"ownerId": "John.Doe",
"startDate": "2014-07-27T13:15:07.000Z",
"activities": [{
"activityType": "Active Activity",
"activityId": 729,
"locationAddress": "1188 El Camino Real, San Bruno, CA, United States",
"startTime": "2014-07-28T04:45:00.000Z",
"customData": {
"title": "Active Activity"
},
"modified": "2014-07-23T13:26:41.000Z"
}],
"senderId": "Johnny.Appleseed",
"status": 8
}
SQLite File:
I have the following entities:
meeting
activity
customData
relationships:
meeting has to-many relationship with activity called activities
activity has to-many relationship with customData
Of course, there is an inverse relationship for each relationship.
customData entity only has one attribute called title
Here is my customData.h
#class Activity;
#interface customData : NSManagedObject
#property (nonatomic, retain) NSString * title;
#property (nonatomic, retain) Activity *activity;
#end
RESKit Mapping:
+(RKEntityMapping *)customDataMapping:(RKEntityMapping *)customDataMapping;
{
[customDataMapping addAttributeMappingsFromDictionary:#{#"title":#"title"}];
customDataMapping.identificationAttributes = #[#"title"];
return customDataMapping;
}
ObjectManager:
meetingMapping = [RESTMappingProvider meetingPutMapping:meetingMapping];
activityMapping = [RESTMappingProvider activityPutMapping:activityMapping];
customDataMapping = [RESTMappingProvider customDataMapping:customDataMapping];
[activityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:kCustomDataRelationship
toKeyPath:kCustomDataRelationship
withMapping:customDataMapping]];
[meetingMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:kActivitiesRelationship
toKeyPath:kActivitiesRelationship
withMapping:activityMapping]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[meetingMapping inverseMapping] objectClass:[Meeting class] rootKeyPath:nil method:RKRequestMethodAny];
NSIndexSet *statusCodeSet = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:meetingMapping
method:RKRequestMethodAny
pathPattern:kMeetupKeyPath
keyPath:nil
statusCodes:statusCodeSet];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[objectManager addRequestDescriptor:requestDescriptor];
[objectManager addResponseDescriptor:responseDescriptor];
[objectManager.HTTPClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[objectManager putObject:anInvite path:kMeetupKeyPath parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog (#"******* OUTBOX OBJECT PUT **********");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
}
}
}
});
Problem:
For some reason, I'm losing relationships between an activity and customData object. As you can see, the internal ID (ZACTIVITY) for CoreData does not always assign Ids, thus, I lose objects because relationships are no longer there. I think its during the PUT call that objects are not assigned the ids.
I read on RESKit forums about using #parent and #metadata, but I'm not sure how to use it, or if that's even a right approach. Please advise.
I'm guessing that the titles of your custom data are not always unique, so, because you use customDataMapping.identificationAttributes = #[#"title"]; and a 1:many relationship some instances of custom data will be disconnected from their old relationship and connected to a new one.
Probably you should remove the identificationAttributes and add a fetch request block which purges out any orphan custom data objects (ones where the relationship is nil) after the data is collected.

RestKit additional data in response

I am using RestKit for mapping data from my api to CoreData entities and i wonder how can i get additional data from response. For example my api return structure like:
{
"items": [
{
"id": 1,
"title": "Title"
},
{
"id": 2,
"title": "Title 2"
}
],
"someParameter": "someValue"
}
i already have right mappings for shared object manager so i just send request:
[[RKObjectManager sharedManager] getObjectsAtPath:#"_api/items"
parameters:parameters
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
//handle success
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
//handle error
}];
How can i get someParameter value in success block? Is this possible?
You will need to tweak your mapping slightly. If you changed it as follows you should be able to get RESTkit to parse the 'someParameter' attribute for you. You need to have two classes (Parent and Child).
The Parent class has 2 attributes (someParameter and an array of Child objects). The addRelationshipMappingWithSourceKeyPath is what ties the Parent and Child object mappings together.
Code:
RKObjectMapping *parentMapping = [RKObjectMapping mappingForClass:[Parent class]];
[beaconActionMapping addAttributeMappingsFromDictionary:#{
#"someParameter" : #"someParameter"
}];
RKObjectMapping *childMapping = [RKObjectMapping mappingForClass:[Child class]];
[beaconMapping addAttributeMappingsFromDictionary:#{
#"id" : #"childId",
#"title" : #"title"
}];
[parentMapping addRelationshipMappingWithSourceKeyPath:#"items" mapping:childMapping];
Class hierarchy:
#interface Parent : NSObject
#property(nonatomic,strong) NSString *someParameter;
#property(nonatomic,strong) NSArray *items; // Array of Child objects
#end
#interface Child : NSObject
#property(nonatomic,strong) NSString *childId;
#property(nonatomic,strong) NSString *title
#end
You can add an additional response descriptor with a key path of someParameter. You can use that with a nil key path mapping to extract the string value into an object of your choice (usually a custom class).

RestKit RKObjectMapping of a list

I am new to RestKit and am trying to map a json object that contains an array of objects my model. I have debugged and found that the response hits my server --> json is return --> RestKit says the mapping was successful and that I have 1 object mapped... However, the errorCode field and the array of businesses (bList) are both null when I do BusinessObjectModel *response = result.array.firstObject;
in the OnSuccessBlock.
Json:
{
"bList":
[
{
"id": 1,
"name": "aName",
"owner": 1,
"category": 1,
}
{
"id": 2,
"name": "aName2",
"owner": 1,
"category": 1,
}
],
"errorCode": 0
}
Want to map this Json to this objective c object:
BussinessObjectModel Object Mapping:
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[BusinessObjectModel class]];
[responseMapping addAttributeMappingsFromDictionary:#{
#"id": #"business_id",
#"name": #"business_name",
}];
return responseMapping;
BModel:
#interface bModel : NSObject
#property (nonatomic, copy) NSNumber *errorCode;
#property (nonatomic, copy) NSMutableArray *bList;
+(RKObjectMapping *) getMapping;
#end
BModel Object Mapping:
RKObjectMapping *bMapping = [BusinessObjectModel getMapping];
RKObjectMapping *buslstMapping = [RKObjectMapping mappingForClass:[BModel class]];
[buslstMapping addAttributeMappingsFromDictionary:#{#"errorCode": #"errorCode"}];
// Define the relationship mapping
[buslstMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil
toKeyPath:nil
withMapping:bussinessMapping]];
return buslstMapping;
Descriptor looks as follows:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:ResponseMapping method:RKRequestMethodAny pathPattern:nil keyPath:#"bList" statusCodes:nil];
EDIT
I want to map the above Json to :
#interface bModel : NSObject
#property (nonatomic, copy) NSNumber *errorCode;
#property (nonatomic, copy) NSMutableArray *bList;
#end
Where bList is an array of the following object:
#interface Business : NSObject
#property (nonatomic, copy) NSNumber *id;
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSNumber *id;
#property (nonatomic, copy) NSNumber *id;
#end
I guess the question is how do I do nested relationships (what would the Response Descriptor have to be for the above relationship)?
Great to see that your using RestKit. Your first helper will be the logging that RestKit provides. Add this line of code do your AppDelegate and watch the console for errors.
// The * will send everything RestKit does to the console
// Replace the * with the module you want to check (Network/CoreData/...)
RKLogConfigureByName("RestKit/*", RKLogLevelTrace);
When looking at your JSON you want to get the objects from the keyPath "bList" on the one hand and on the other hand the error code or message when something goes wrong. RestKit provides a build in error handling to get that information out of your JSON.
Init the RKObjectMapping for the RKErrorMessage class and add a RKResponseDescriptor to your requests with the right keyPaths including the range of status codes (here using client errors). RestKit will automatically detect the error code (when sent within the header) and apply the mapping to get the content of the error message.
// Init error mapping
RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:#"errorMessage"]];
// Add mapping as response descriptor
RKResponseDescriptor *errorDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:errorMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#"message" // Edit the keyPath to the value of your JSON (e.g. errorCode)
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)];
[RKObjectManager.sharedManager addResponseDescriptor:errorDescriptor];
To get the error message when a failure occurs, you simply get the message object. When using a block to get objects, you can use the userInfo dictionary from the given NSError.
RKErrorMessage *errorMessage = [[error.userInfo objectForKey:RKObjectMapperErrorObjectsKey] firstObject];
NSLog(#"Error: %#", errorMessage);
Now you can simplify your object model a bit and concentrate on mapping the BusinessObjectModel. When mapping the object using the dictionary, you need to check of your local attributes matches the value in your JSON.
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[BusinessObjectModel class]];
[responseMapping addAttributeMappingsFromDictionary:#
{
#"value_from_remote_json": #"value_in_local_object", // e.g. #"id" : #"business_id"
...
}];
return responseMapping;
You don't need to use a RKRelationshipMapping any more. Reconfigure your objects/mappings and try again. The logging will show you the provided mapping and if the mapping operations are working. Last bit not least make sure that the mapping is in memory when using it by throwing an NSAssert error.
RKObjectMapping *bMapping = [BusinessObjectModel getMapping];
NSAssert(bMapping, #"bMapping mapping must not be nil");
Edit
To map values without a keyPath (like the "errorCode" field) additionally to the mapping of your objects, you'll need to provide an object with an according mapping. Taking the example from the documentation you'll end with something like:
// Init object
#interface RKErrorCode : NSObject
#property (nonatomic) NSNumber *errorCode;
#end
// Init mapping
RKObjectMapping *codeMapping = [RKObjectMapping mappingForClass:[RKErrorCode class]];
[codeMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:#"errorCode"]];
// Add response descriptor for request
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:codeMapping method:RKRequestMethodAny pathPattern:nil keyPath:#"errorCode" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
Your response descriptor shouldn't have keyPath:#"bList", it should be set to nil as you don't want to drill in.
It also shouldn't use ResponseMapping based on the structure of your mappings, it should use the other mapping.
Your mapping is also wrong here:
#{
#"business_id": #"business_id",
#"business_name": #"business_name",
}];
It should be:
#{
#"id": #"business_id",
#"name": #"business_name",
}];
Because this specifies the JSON names and the core data names.
To fix your new issues, put this back:
[buslstMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"bList" toKeyPath:#"bList"
And this:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:buslstMapping method:RKRequestMethodAny pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Found the solution and it looks something like this:
RKObjectMapping *bModelMapping = [RKObjectMapping mappingForClass:[business class]];
[bModelMapping addAttributeMappingsFromDictionary:#{
#"id": #"business_id",
#"name": #"business_name",
}];
RKObjectMapping *buslstMapping = [RKObjectMapping mappingForClass:[bModel class]];
[buslstMapping addAttributeMappingsFromDictionary:#{#"errorCode": #"errorCode"}];
// Define the relationship mapping
[buslstMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"bList"
toKeyPath:#"bList" bModelMapping]];
return buslstMapping;
Also Change the following:
#property (nonatomic, copy) NSMutableArray *bList;
to
#property (nonatomic, retain) NSArray *bList;
This gives me a bModel object with an error code value and a bList which is an array of business which can then be cast to a business by doing the following Business *business = [bModel.blist firstObject];

Foreign key relationship mapping with RestKit

I'm totally new to RestKit and am struggling somewhat.
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
My application logic looks like this:
// 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];
I can't for the life of me work out how to get RestKit to populate the team Property of the user objects.
I've look at so many posts but nothing I try works, is this not a usual use case?
Does anyone know how to do this, help would be very appreciated!
Thanks.
You need to add a transient attribute to your User entity which holds the associated teamId. This needs to be added to your userMapping.
Then, you need to add a relationship definition to your userMapping:
[userMapping addConnectionForRelationship:#"team" connectedBy:#{ #"teamId": #"teamId" }];
This gives RestKit the information it needs to make the connection and instructs it to make the connection as part of the mapping operation.

Resources