Restkit property mapping Failed Transformation error - ios

this is what my sample code looks like:
{
"name": "Ahmad Mansour",
"subjects": [
{
"parent_subject_name": "Arabic",
"subject_name": "Shafahi",
"exams": [
{
"score": "30.00",
"exam_name": "Sa3i 1 "
},
{
"score": "50.00",
"exam_name": "sa3i 2"
},
{
"score": "100.00",
"exam_name": "First Semester Exam"
}
]
},
{
"parent_subject_name": "Arabic",
"subject_name": "Khati",
"exams": [
{
"score": "50.00",
"exam_name": "Sa3i 1 "
},
{
"score": "60.00",
"exam_name": "sa3i 2"
},
{
"score": "95.00",
"exam_name": "First Semester Exam"
}
]
},
for the subject entity.. my mapping works just fine:
RKEntityMapping *subjectEntityMapping = [RKEntityMapping mappingForEntityForName:kSubjectIdentity inManagedObjectStore:model.managedObjectStore];
[subjectEntityMapping addAttributeMappingsFromDictionary:#{ #"subject_name": #"name",
#"parent_subject_name" :#"parent_name"
}];
subjectEntityMapping.identificationAttributes = #[ #"name" ];
RKResponseDescriptor *studentResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:subjectEntityMapping pathPattern:kGradesPath keyPath:#"subjects" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[model.objectManager addResponseDescriptor:studentResponseDescriptor];
but when i do the exam score mapping.. things blow up:
RKEntityMapping *examEntityMapping = [RKEntityMapping mappingForEntityForName:kExamIdentity inManagedObjectStore:model.managedObjectStore];
[examEntityMapping addAttributeMappingsFromDictionary:#{ #"exams.exam_name": #"name" }];
examEntityMapping.identificationAttributes = #[ #"name" ];
RKResponseDescriptor *examResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:examEntityMapping pathPattern:kGradesPath keyPath:#"subjects" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[model.objectManager addResponseDescriptor:examResponseDescriptor];
i get the following error:
E restkit.object_mapping:RKMappingOperation.m:431 Failed transformation of value at keyPath 'exams.exam_name' to representation of type 'NSString': Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3002 "Failed transformation of value '(
"Sa3i 1 ",
"sa3i 2",
"First Semester Exam"
)' to NSString: none of the 2 value transformers consulted were successful." UserInfo=0x9a508a0 {detailedErrors=(
"Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3002 \"The given value is not already an instance of 'NSString'\" UserInfo=0x9a50800 {NSLocalizedDescription=The given value is not already an instance of 'NSString'}",
"Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3000 \"Expected an `inputValue` of type `NSNull`, but got a `__NSArrayI`.\" UserInfo=0x9a50830 {NSLocalizedDescription=Expected an `inputValue` of type `NSNull`, but got a `__NSArrayI`.}"
I also tried this mapping, but i get the exact same error:
[examEntityMapping addAttributeMappingsFromDictionary:#{ #"exam_name": #"name" }];
examEntityMapping.identificationAttributes = #[ #"name" ];
RKResponseDescriptor *examResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:examEntityMapping pathPattern:kGradesPath keyPath:#"subjects.exams" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
ideas?

You shouldn't have a response descriptor for exams. It's nested data in your subject so it should be mapped using a relationship on the subject mapping.
Using the response descriptor doesn't work because you're trying to map into 2 arrays when the mapping only caters for one. Hence you get an error when RestKit tries to convert an array into a string.
Also, for your exam mapping you should probably specify multiple attributes for the unique identity as exam names are used repeatedly for different instances...

Related

Map only on element of a one to many relationships

I'm stuck with the following problem. I have a relationships one_to_many between a Event and Comment. One Event can have many Comment but a Comment has belongs_to only one Event.
Until here, everything is fine. Now, when I'm adding a comment, I would like to map only this new comment. That means I'm using my relationship from Comment to Moment.
I have some troubles with the mapping that I'm not able to solve. My error is at the end of this post after all the description.
I'm receiving this JSON:
"comment": {
"id": 17,
"commentable_id": 12,
"commentable_type": "Moment",
"content": "That's it ! ",
"created_at": "2014-06-20T18:17:42Z",
"updated_at": "2014-06-20T18:17:42Z",
"user_id": 1,
"creator": {
"id": 1,
"email": "test#test.com",
"firstname": "Bobby",
"lastname": "Stouket",
"gender": 0,
"created_at": "2014-04-06T17:48:11Z",
"updated_at": "2014-06-20T18:17:26Z"
}
}
Here is my comment mapping:
RKEntityMapping *commentMapping = [RKEntityMapping mappingForEntityForName:#"Comment" inManagedObjectStore:store];
commentMapping.identificationAttributes = #[ #"commentId"];
[commentMapping addAttributeMappingsFromDictionary:#{
#"id" : #"commentId",
#"updated_at": #"updatedAt",
#"created_at": #"createdAt",
#"user_id": #"userId",
#"commentable_id": #"commentableId",
#"commentable_type": #"commentableType",
#"content": #"content"
}];
RKEntityMapping *userCreatorMapping = [APICallUser RKGetUserMappingOnlyWithAvatarForManagedObjectStore:store];
[commentMapping addConnectionForRelationship:#"creator" connectedBy:#{#"userId": #"userId"}];
[commentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"creator"
toKeyPath:#"creator"
withMapping:userCreatorMapping]];
Here is my code for my moment mapping (with the association with comments which is working) :
RKEntityMapping *momentMapping = [RKEntityMapping mappingForEntityForName:#"Moment" inManagedObjectStore:store];
momentMapping.identificationAttributes = #[ #"momentId"];
[momentMapping addAttributeMappingsFromDictionary:#{
#"id" : #"momentId",
#"creator.id" : #"creatorId",
#"created_at" : #"createdAt",
#"updated_at" : #"updatedAt"
}];
RKEntityMapping *commentMapping = [APICallComment RKGetCommentMappingForManagedObjectStore:store];
[commentMapping addConnectionForRelationship:#"moment" connectedBy:#{#"commentableId":#"momentId"}];
[momentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"comments"
toKeyPath:#"comments"
withMapping:commentMapping]];
There is one more thing to know is that a comment can be on a moment or on a photo. According to my JSON, I don't think I need an RKDynamicMapping but I'm not sure.
Here is the code when I'm using my mapping. The request is send successfully and I receive the JSON written before.
KEntityMapping *commentMapping = [APICallComment RKGetCommentMappingForManagedObjectStore:self.appDelegate.managedObjectStore];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:commentMapping
method:RKRequestMethodPOST
pathPattern:APICallCommentCreateCommentsRouteName
keyPath:#"comment"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[session.objectManager addResponseDescriptor:responseDescriptor];
//session.objectManager.requestSerializationMIMEType=RKMIMETypeJSON;
Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No mappable object representations were found at the key paths searched." UserInfo=0xb8a9150 {DetailedErrors=(), NSLocalizedFailureReason=The mapping operation was unable to find any nested object representations at the key paths searched: comments, device, devices
The representation inputted to the mapper was found to contain nested object representations at the following key paths: comment
This likely indicates that you have misconfigured the key paths for your mappings., NSLocalizedDescription=No mappable object representations were found at the key paths searched., keyPath=null}
Edit:
Here is the result of the code line session.objectManager.requestDescriptor. It's really weird. I can see only 1 object in the NSArray. When I print it I can read:
Printing description of $1:
<__NSArrayI 0xbd61010>(
<RKRequestDescriptor: 0xbd12bb0 method=(POST) objectClass=BasicLocation rootKeyPath=position : <RKObjectMapping:0xbd40b70 objectClass=NSMutableDictionary propertyMappings=(
"<RKAttributeMapping: 0xbd545d0 latitude => lat>",
"<RKAttributeMapping: 0xbd58430 longitude => lng>"
)>>
)
Nowhere I've written that positionshould be the rootKeyPath and my other attributes are not here (content, commentableType, userId, createdAt, updatedAt, commentId).
Thank you for your help.
You create:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:commentMapping
method:RKRequestMethodPOST
pathPattern:APICallCommentCreateCommentsRouteName
keyPath:#"comment"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
but you can't ever add it to the object manager, because it only understands comments, device, devices.
That would seem to be your main issue.
You wouldn't usually do this:
[commentMapping addConnectionForRelationship:#"creator" connectedBy:#{#"userId": #"userId"}];
[commentMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"creator"
toKeyPath:#"creator"
withMapping:userCreatorMapping]];
because you are supplying 2 different mappings for exactly the same content and relationship where you only need one because the user information is nested inside the comment information. So, you can remove the foreign key mapping (addConnectionForRelationship:).
The mapping was good but the mistake comes from here:
[RKResponseDescriptor responseDescriptorWithMapping:commentMapping
method:RKRequestMethodGET
pathPattern:HERE
keyPath:#"comment"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
I didn't write the path pattern. This variable changed and everything works perfectly.

Wrong RKResponseDescriptor - nested object found but not mappable

I have the following entity mapping and descriptor:
RKEntityMapping *responseUserMapping = [APICallUser RKGetUserMappingForManagedObjectStore:self.appDelegate.managedObjectStore];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseUserMapping
[session.objectManager addResponseDescriptor:responseDescriptor];
method:RKRequestMethodPOST
pathPattern:APICallUserCreatePattern
keyPath:#"user"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Here is the description of the method RKGetUserMappingForManagedObjectStore
+ (RKEntityMapping *) RKGetUserMappingForManagedObjectStore:(RKManagedObjectStore *) store{
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:#"User" inManagedObjectStore:store];
userMapping.identificationAttributes = #[ #"userId" ];
[userMapping addAttributeMappingsFromDictionary:#{
#"id" : #"userId",
#"email" : #"email",
#"firstname" : #"firstName",
#"lastname" : #"lastName",
#"gender" : #"gender",
#"time_zone" : #"timeZone",
#"created_at" : #"createdAt",
#"nickname" : #"pseudo",
#"facebook_id" : #"facebookId",
#"facebook_link_asked_at" : #"lastQueryForFacebookLinkDate",
#"birthday" : #"birthDate",
#"city" : #"city",
#"country" : #"country",
#"sign_in_count" : #"signInCount",
#"facebook_token" : #"facebookToken",
#"facebook_token_expires_at" : #"facebookExpiration",
#"avatar.id" : #"avatarPhotoId"
}];
RKEntityMapping *photoMapping = [APICallPhoto RKGetPhotoMappingForManagedObjectStore:store];
photoMapping.setNilForMissingRelationships = YES;
[userMapping addConnectionForRelationship:#"avatarPhoto" connectedBy:#{#"avatarPhotoId" : #"photoId"}];
//[photoMapping addConnectionForRelationship:#"avatarUsers" connectedBy:#{ #"photoId": #"avatarPhotoId" }];
[userMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"avatar" toKeyPath:#"avatarPhoto" withMapping:photoMapping]];
return userMapping;
}
And the code for the method RKGetPhotoMappingForManagedObjectStore
+ (RKEntityMapping *) RKGetPhotoMappingForManagedObjectStore:(RKManagedObjectStore *) store{
RKEntityMapping *photoMapping = [RKEntityMapping mappingForEntityForName:#"Photo" inManagedObjectStore:store];
photoMapping.identificationAttributes = #[ #"photoId" ];
[photoMapping addAttributeMappingsFromDictionary:#{
#"id" : #"photoId",
#"moment_id" : #"momentId",
#"user_id" : #"userId",
#"title" : #"title",
#"description" : #"photoDescription",
#"file.thumb_url" : #"thumbnailDistURL",
#"file.mini_url" : #"miniDistURL",
#"file.little_url" : #"littleDistURL",
#"file.medium_url" : #"mediumDistURL",
#"file.public_url" : #"originalDistURL"
}];
/*RKEntityMapping *momentMapping = [APICallMoment RKGetMomentMappingForManagedObjectStore:store];
[momentMapping addConnectionForRelationship:#"photos" connectedBy:#{ #"momentId": #"momentId" }];
[photoMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"moment" toKeyPath:#"moment" withMapping:momentMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:photoMapping method:RKRequestMethodAny pathPattern:nil keyPath:#"photos" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
*/
return photoMapping;
}
This is my json that my app received:
{
"user": {
"id": 38,
"email": "test#test.com",
"firstname": "bob",
"lastname": "tonny",
"gender": 0,
"created_at": "2014-04-19T11:00:55Z",
"updated_at": "2014-04-19T11:00:55Z",
"nickname": "bobby",
"facebook_id": null,
"birthday": "1990-02-14",
"city": "",
"country": "",
"facebook_token": null,
"facebook_token_expires_at": null,
"time_zone": "Europe/Paris",
"facebook_link_asked_at": null,
"sign_in_count": 0,
"confirmed": false,
"badge": {
"permanent": 0,
"contextual": 0
},
"avatar": null
}
}
You can see that there is no relation with device or devices here. But I have the exact following error:
error=Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No mappable object representations were found at the key paths searched." UserInfo=0xd0c1770 {DetailedErrors=(
), NSLocalizedFailureReason=The mapping operation was unable to find any nested object representations at the key paths searched: device, devices
The representation inputted to the mapper was found to contain nested object representations at the following key paths: user
This likely indicates that you have misconfigured the key paths for your mappings., NSLocalizedDescription=No mappable object representations were found at the key paths searched., keyPath=null}
I'm currently not able to find where the problem comes from.
The only relation between User and Device is set on the .xcdatamodelId like you can see on the following pictures:
relationship for User
relationship for Device
I took a lot at the descriptors: session.objectManager.responseDescriptors. There are several descriptors but none about any devices.
If anyone can just see where I'm missing something, I would really like to know it.
Thank you in advance.
I found the solution. It was not obvious at all. After adding my descriptor to the objectManager, I did that:
session.objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
That solved completely my problem. I don't know why it's important to precise here because I already set this property a long time ago on my code..
Edit: It WAS working ! I didn't touch anything but now it's not working.
Edit 2: I finally got it :
I was using
`[session.objectManager addResponseDescriptor:responseDescriptor];
session.objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[[RKObjectManager sharedManager] managedObjectRequestOperationWithRequest:request managedObjectContext:session.objectManager.managedObjectStore.mainQueueManagedObjectContext success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)`
I changed [RKObjectManager sharedManager] by my variable session.objectManager and everything work fine !
I hope it will help someone else.

Using RKDynamicMapping on Foursquare's Lists API to capture lists

I'm looking to get all of my Foursquare Lists into Core Data. I'd like to use Restkit to accomplish this. The structure of the /v2/users/self/lists response is:
"response": {
"lists": {
"count": 8,
"groups": [
{
"type": "created",
"name": "Lists You've Created",
"count": 6,
"items": [
{
"id": "13250/todos",
"name": "My to-do list", ...
}
{
"id": "13251/something",
"name": "Some List", ...
},
{
"id": "13252/somethingelse",
"name": "Some Other List", ...
}
]
},
{
"type": "followed",
"name": "Lists You've Saved",
"count": 1,
"items": [
{
"id": "5105e3cae4b0e721ca7b400a",
"name": "Portland's Best Coffee - 2012", ...
}
{
...
}
]
}
]
}
As you can see there are 2 lists under the keyPath response.lists.groups. Ultimately I'd like to merge those 2 lists into 1, but I'd be happy with getting 2 separate lists.
I've set up my mappings as follows:
RKEntityMapping* listMapping = [RKEntityMapping mappingForEntityForName:[FOFSList entityName]
inManagedObjectStore:objectManager.managedObjectStore];
[listMapping addAttributeMappingsFromDictionary:#{
#"id": #"listID",
#"title": #"name",
#"description": #"desc",
#"user": #"user",
#"following": #"following",
#"collaborative": #"collaborative",
#"canonicalUrl": #"canonicalUrl",
#"venueCount": #"venueCount",
#"visitedCount": #"visitedCount"
}];
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
[listMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil
toKeyPath:#"items"
withMapping:dynamicMapping]];
RKResponseDescriptor *listResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:listMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#"response.lists.groups"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:listResponseDescriptor];
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if ([[representation valueForKey:#"type"] isEqualToString:#"created"]) {
return listMapping;
} else if ([[representation valueForKey:#"type"] isEqualToString:#"followed"]) {
return listMapping;
}
return nil;
}];
listMapping.identificationAttributes = #[ #"listID" ];
I end up with an error:
* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key propertyMappings.'
Am I supposed to be using RKDynamicMappings? Is there some trick that I'm missing for parsing a response that is styled like this?
For those that are interested, I got a little bit creative with the RKResponseDescriptor
RKResponseDescriptor *listResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:listMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:#"response.lists.groups.#distinctUnionOfArrays.items"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
See the collection operation #distinctUinionOfArrays was ultimately what got me what I needed. It makes a union of the 2 groups arrays, then I grab the items key from each of the objects in the union of the arrays.
At the moment the dynamic mapping is serving as a filter on the type. That's fine if it's what you want and is the correct way to achieve the filter. But, you're applying that mapping in the wrong way.
The dynamic mapping should be supplies as the mapping for the response descriptor. It analyses the incoming object and returns the appropriate mapping to apply.
You need a new, non-dynamic, mapping to handle the nested items.
Your other question about merging can't be handled during the mapping, but it could be done by adding a method to the destination class which is called with the mapped array and it merges with an existing array and pushes the merged result into the true instance variable. The mapping destination would be the method instead of the instance variable.

RESTKIT request mapping for unknown keys

{
"type": "at or leave",
"time": "XXXX",
"place_name": "Xx",
"place_id": "xx",
"place_attributes": {
"key": "val",
"key2": "val2",
},
"place_type": "public or private"
}
i want to post json like above.But placeAttributes dictionary in my app will be having unknown number of keys which are needed to be mapped with "place_attributes" in json above.
Created a NSDictionary* placeAttributes property in my request mapping class, mapped it to place_attributes key in json and directly assigned my dictionary to placeAttributes.
RKObjectMapping* map = [RKObjectMapping requestMapping];
[map addAttributeMappingsFromDictionary:#{
#"type":#"type",
#"time":#"time",
#"place_name":#"place_name",
#"place_id":#"place_id",
#"place_type":#"place_type",
#"placeAttributes":#"place_attributes"
}];

RestKit Add Property Mapping and Relationship Mapping

Please guide me about following problem.
I have two entities with relationship as shown following image
I am using latest version of RestKit with iOS 7
Now in my appDelegate i am using following mapping for "List" Entity
NSDictionary *listObjectMapping = #{
#"listID" : #"listID",
#"listName" : #"listName",
#"listSyncStatus" : #"listSyncStatus"
};
RKEntityMapping *listEntityMapping = [RKEntityMapping mappingForEntityForName:#"List" inManagedObjectStore:managedObjectStore];
[listEntityMapping addAttributeMappingsFromDictionary:listObjectMapping];
listEntityMapping.identificationAttributes = #[ #"listID" ];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:listEntityMapping
method:RKRequestMethodGET
pathPattern:#"/api/lists"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:responseDescriptor];
//Inverse mapping, to perform a POST
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[listEntityMapping inverseMapping]
objectClass:[List class]
rootKeyPath:nil
method:RKRequestMethodPOST];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"application/json"];
[objectManager addRequestDescriptor:requestDescriptor];
//Inverse mapping, to perform a PUT
requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[listEntityMapping inverseMapping]
objectClass:[List class]
rootKeyPath:nil
method:RKRequestMethodPUT];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"application/json"];
[objectManager addRequestDescriptor:requestDescriptor];
and using following mapping for my Task object
NSDictionary *taskObjectMapping = #{
#"listID" : #"listID",
#"taskID" : #"taskID",
#"taskName" : #"taskName",
#"taskCompletionStatus" : #"taskCompletionStatus",
#"taskSyncStatus" : #"taskSyncStatus"
};
RKEntityMapping *taskEntityMapping = [RKEntityMapping mappingForEntityForName:#"Task" inManagedObjectStore:managedObjectStore];
[taskEntityMapping addAttributeMappingsFromDictionary:taskObjectMapping];
taskEntityMapping.identificationAttributes = #[ #"taskID" ];
RKResponseDescriptor *taskResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:taskEntityMapping
method:RKRequestMethodGET
pathPattern:#"/api/list/:id"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptor:taskResponseDescriptor];
//Inverse mapping, to perform a POST
RKRequestDescriptor *taskRequestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[taskEntityMapping inverseMapping]
objectClass:[Task class]
rootKeyPath:nil
method:RKRequestMethodPOST];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"application/json"];
[objectManager addRequestDescriptor:taskRequestDescriptor];
//Inverse mapping, to perform a PUT
taskRequestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[taskEntityMapping inverseMapping]
objectClass:[Task class]
rootKeyPath:nil
method:RKRequestMethodPUT];
objectManager.requestSerializationMIMEType = RKMIMETypeJSON;
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
[RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:#"application/json"];
[objectManager addRequestDescriptor:taskRequestDescriptor];
Now my question is how to add relationship mapping between these two entites ?
What would be proper way ?
If i use i use following line of code
[taskEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"list.listID"
toKeyPath:#"listID"
withMapping:listEntityMapping]];
a runtime error occurs saying "Unable to add mapping for keyPath listID, one already exists"
and if i use this
[listEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"listID"
toKeyPath:#"list.listID"
withMapping:taskEntityMapping]];
app crashes with this error the entity List is not key value coding-compliant for the key "list".'
and if i omit the above code and try to get listID from relationship
task.list.listID
it gives me "0". Can anyone tell me what exactly am i doing wrong or what should i do to accomplish above task. I can give more details on this if needed.
EDIT
but my request to all list returns following json
GET www.mydomain.com/api/lists
[
{"listID":"42","listName":"List 4","listSyncStatus":"1"},
{"listID":"41","listName":"List 3","listSyncStatus":"1"},
{"listID":"40","listName":"List 2","listSyncStatus":"1"}
]
and request to single list will return its task as follows
GET www.mydomain.com/api/list/42
[
{"taskID":"22","listID":"42","taskName":"Task 2","taskSyncStatus":"1","taskCompletionStatus":"1"},
{"taskID":"21","listID":"42","taskName":"Task 1","taskSyncStatus":"1","taskCompletionStatus":"1"}
]
i.e there is no cascading relationship in returned in json. is this wrong way or what am i missing here ?
Corrected After Accepting Answer
It turns out i was returning wrong json i.e. the returned json has no relationship in it while the iOS model has a relationship "tasks" so i edited my rest api to return correct nested json which is like below
[ { "listID" : "96",
"listName" : "List 1",
"listSyncStatus" : "1",
"tasks" : [ { "taskCompletionStatus" : "1",
"taskID" : "67",
"taskName" : "Task 2",
"taskSyncStatus" : "1"
},
{ "taskCompletionStatus" : "1",
"taskID" : "66",
"taskName" : "Task 1",
"taskSyncStatus" : "1"
}
]
},
{ "listID" : "97",
"listName" : "List 2",
"listSyncStatus" : "1",
"tasks" : [ { "taskCompletionStatus" : "1",
"taskID" : "69",
"taskName" : "Task 1",
"taskSyncStatus" : "1"
},
{ "taskCompletionStatus" : "1",
"taskID" : "68",
"taskName" : "Task 1",
"taskSyncStatus" : "1"
}
]
}
]
after returning above nested json, everything works like charm, specially this line
[listEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"tasks"
toKeyPath:#"tasks"
withMapping:taskEntityMapping]];
Hope this helps grasping relationship concepts for people like me out there.
You modal diagram shows that you have one-to-many relationship (One list has many tasks).
As far as i know, in this case you need to add relationship mapping on List entity only, no need on Task entity. Also for one-to-many relationship, you don't need to add list relationship under Task entity.
Your entities relationship should look like this
So try following
[listEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"YOUR_JSON_KEYPATH_HERE" toKeyPath:#"tasks" withMapping: taskEntityMapping]];
IMPORTANT
In above method
FromKeyPath parameter should be the name of your JSON key where the relationship starts.
toKeyPath parameter should be the relationship name that you have mentioned in Entity diagram. i.e; tasks.
withMapping should be the mapping of many entity. In you case taskEntityMapping
Hope this fix the issue.
Not sure why this is not working, but you can try to create the relationship mapping like this:
[taskEntityMapping addConnectionForRelationship:#"list" connectedBy:#{ #"listId": #"listId" }];
[listEntityMapping addConnectionForRelationship:#"tasks" connectedBy:#{ #"listId":#"listId"}];

Resources