RestKit - Object Mapping functions not found - objective-c

I'm naïvely trying to follow the guidelines for mapping one of my CoreData classes with RestKit 0.20
#import <RestKit/RestKit.h>
...
RKObjectMapping *mymap =
[RKObjectMapping mappingForClass: NSClassFromString(#"MY_CLASS")];
[mymap mapAttributes:#"field1", #"field2", nil];
But
No visible #interface for 'RKObjectMapping' declares the selector 'mapAttribute'
If I type [mymap map, I see only these 2 functions in the completion list
id mappingForDestinationKeyPath:(NSString *)
id mappingForSourceKeyPath:(NSString *)
What am I doing wrong ?
An other example, when I try to use the shared RKObjectManager
[[RKObjectManager sharedManager].mappingProvider setMapping:map forKeyPath:#"/"];
It can't find the member mappingProvider

I think this is a problem with the wiki page, mapAttributes: is not found in the RKObjectMapping docs (http://restkit.org/api/master/Classes/RKObjectMapping.html). I think the wiki page is out of date, use this one instead: https://github.com/RestKit/RestKit/wiki/Object-Mapping
You should use the addAttributeMappingsFromDictionary method instead:
[mymapp addAttributeMappingsFromDictionary:#{#"field1" : #"field1"}];
Also mappingProvider is from pre-0.20 rest kit, and has been replaced with response descriptors (objects which are used to determine which mapping to use for a response)
RKResponseDescriptor *descriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping pathPattern:nil keyPath:#"key_path" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:descriptor];

Use mapping like this:
RKManagedObjectMapping * mymap = [RKManagedObjectMapping mappingForClass:[MY_CLASS class] inManagedObjectStore:self.objectStore];
mymap.setDefaultValueForMissingAttributes = YES;
mymap.primaryKeyAttribute = #"MY_CLASS_ID";
mymap.rootKeyPath = #"ROOT_PATH_OF_SERVICE";
[mymap mapKeyPathsToAttributes:
#"WEB_SERVICE_ATTRIBUTE1", #"DATA_MODAL_ATTRIBUTE1",
#"WEB_SERVICE_ATTRIBUTE2", #"DATA_MODAL_ATTRIBUTE2",
#"WEB_SERVICE_ATTRIBUTE3", #"DATA_MODAL_ATTRIBUTE3",
nil];

Related

RestKit: how to map URL param to object attribute

I've got REST service method like this one
/GetOfficeDocument?officeId=259
which returns an array of documents. Document in the app is a NSManagedObject object that has relationship to an office. How can I map officeId param to office relationship of my Document?
I know I should override objectLoader:willMapData:, but I don't know what exactly should I do inside of this method. The documentation is useless.
UPD. The response of the server looks like this:
[{"AddedDate":"\/Date(1261484400000+0400)\/","Title":"Some text","Uri":"\/Document\/News\/851"}]
As you see, officeId is not contained in response, only in URL. I can extract it in objectLoader:willMapData: using
[[[loader URL] queryParameters] objectForKey:#"officeId"]
but where should I put it next? Mappable data parameter is a mutable array, what should I place there? No idea.
You could try to inject the OfficeId value in each document item returned in the response like so:
- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout __autoreleasing id *)mappableData
{
NSString *officeId = [[[loader URL] queryParameters] objectForKey:#"officeId"];
NSMutableArray *newMappableData = [[NSMutableArray alloc] initWithCapacity:[*mappableData count]];
for (NSDictionary *documentDict in *mappableData)
{
NSMutableDictionary = newDocumentDict = [documentDict mutableCopy];
[newDocumentDict setObject:officeId forKey:#"OfficeId"];
[newMappableData addObject:newDocumentDict];
}
*mappableData = newMappableData;
}
And use something similar to the following in your Document mapping:
[documentMapping mapAttributes:#"AddedDate", #"Title", #"Uri", #"OfficeId", nil];
[documentMapping mapKeyPath:#"" toRelationship:#"office" withMapping:officeMapping];
[documentMapping connectRelationship:#"office" withObjectForPrimaryKeyAttribute:#"OfficeId"];
I usually add the RKObjectMapping to the managedObject class
Add this to your Document.h
+ (RKObjectMapping *)objectMapping;
Add this method to your Document.m
+ (RKObjectMapping *)objectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[self class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
mapping.primaryKeyAttribute = #"word";
[mapping mapKeyPath:#"word" toAttribute:#"word"];
[mapping mapKeyPath:#"min_lesson" toAttribute:#"minLesson"];
}
Off course you should change the key paths to your Document object properties. each pair is the name of the key on the server responds and it's corresponded keyPath on your managedObject.
Then when you initialize the objectManager you can set the mapping for each managedObject you have.
RKManagedObjectStore *store = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil delegate:self];
objectManager.objectStore = store;
//set the mapping object from your Document class
[objectManager.mappingProvider setMapping:[SRLetter objectMapping] forKeyPath:#"Document"];
YOu can find a great tutorial here - RestKit tutorial. In the middle of the article you will find data about mapping.

RestKit many to many relationship saves new rows in both join table and null values in main table

I use RestKit to cache data from a remote server locally. In it I have a many to many relationship between Category <<-->> News. The mapping seems to work properly, despite that it also saves null values in my Category table (it saves the correct categories too). Like the image below:
It seems to save 30 null rows, I also have 30 (not null) rows in my join table so there might be a correlation here.
The JSON that I get looks like this: "categories":[{"category_id":1},{"category_id":4}]
I have two custom model objects that inherits from NSManagedObject.
#interface News : NSManagedObject
[...]
#property (nonatomic, retain) NSSet *categories;
#end
#interface Category : NSManagedObject
[...]
#property (nonatomic, retain) NSSet *news;
#end
I use #dynamic on both.
My mappings looks like this:
RKManagedObjectMapping *categoryMapping = [RKManagedObjectMapping mappingForClass:[Category class] inManagedObjectStore:objectManager.objectStore];
categoryMapping.primaryKeyAttribute = #"categoryId";
categoryMapping.rootKeyPath = #"categories";
[categoryMapping mapKeyPath:#"id" toAttribute:#"categoryId"];
[...]
RKManagedObjectMapping* newsMapping = [RKManagedObjectMapping mappingForClass:[News class] inManagedObjectStore:objectManager.objectStore];
newsMapping.primaryKeyAttribute = #"newsId";
newsMapping.rootKeyPath = #"news";
[newsMapping mapKeyPath:#"id" toAttribute:#"newsId"];
[...]
// Categories many-to-many (not fully working yet).
[newsMapping mapKeyPath:#"categories" toRelationship:#"categories" withMapping: categoryMapping];
// Register the mappings with the provider
[objectManager.mappingProvider setObjectMapping:newsMapping forResourcePathPattern:#"[path-to-JSON]"];
[objectManager.mappingProvider setObjectMapping:categoryMapping forResourcePathPattern:#"[path-to-JSON]"];
I fetch the data like this (much like the Twitter RestKit example):
- (id)init
{
self = [super init];
if (self) {
[self loadCategories];
[self loadCategoriesFromDataStore];
[self loadNews];
[self loadNewsFromDataStore];
}
return self;
}
- (void)loadCategoriesFromDataStore
{
NSFetchRequest* request = [Category fetchRequest];
NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:#"categoryId" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:descriptor]];
_categories = [Category objectsWithFetchRequest:request];
}
- (void)loadNewsFromDataStore
{
NSFetchRequest* request = [News fetchRequest];
NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:#"createdAt" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:descriptor]];
_news = [News objectsWithFetchRequest:request];
}
- (void)loadCategories
{
// Load the object model via RestKit
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[objectManager loadObjectsAtResourcePath:#"[link-to-JSON]" delegate:self];
}
- (void)loadNews
{
// Load the object model via RestKit
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[objectManager loadObjectsAtResourcePath:#"[link-to-JSON]" delegate:self];
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
[[NSUserDefaults standardUserDefaults] synchronize];
[self loadCategoriesFromDataStore];
[self loadNewsFromDataStore];
}
Any ideas what I'm doing wrong?
Note:
It also seems to save 30 rows to the join table when there are 15 News, I don't know if this is the normal behavior for join tables.
Update: It also maps the the wrong category id's in the join table (ie. category 66, a null row).
update 2: JSON get request for my Category {"categories":{[...], "id":1, [...]}
This line is wrong:
[categoryMapping mapKeyPath:#"id" toAttribute:#"categoryId"];
it should be
[categoryMapping mapKeyPath:#"category_id" toAttribute:#"categoryId"];
EDIT:
The object mapping you have will map two JSON formats.
1) {"categories":[{"id":7},{"id":12}]} when you have the resource path #"[path-to-JSON]"
2) {"news":[{"id":5, "categories":[{"id":7}]}]} when you have the resource path #"[path-to-JSON]"
(I presume those actual paths are different by the way)
Anything else, such as the JSON you have posted at the top of your question, will not work. The problem you are seeing is because the primary key attribute can not be found in your JSON, so when the object is saved to core data a new entity is created with no primary key.

Mapping a JSON response to an object using RestKit and Objective-C

I am relatively new to Objective-C and am attempting to use RestKit to receive a JSON response from a web service. I have successfully received the data back to my application, which looks like this viewing the response:
{id:"1","Translation":"Test"}
I would like to map this translation to my "Translation" object in my application, but have tried a few different ways but am not sure how to achieve this.
So my questions are:
How can I map this response to my Translation object
Am I doing this correctly, creating a method to complete this call outwit my view controller?
My Translation Object
#implementation Translation
#synthesize identifier = _identifier;
#synthesize translation = _translation;
- (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithKeysAndObjects:
#"id", #"identifier",
#"translation", #"translation",
nil];
}
#end
My Translate Method
- (NSString *)performTranslation:(NSString *)translation
{
NSString *data = [[NSString alloc] initWithFormat:#"{\"SourceId\": \"%#\",\"RegionTag\": \"%#\",\"InputString\": \"%#\"}", #"1", #"Glasgow", translation];
NSString *post = data;
RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:#"http://my.url.com/Translation/Translate"]];
MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = post;
MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:#"application/json", #"Content-Type", #"application/json", #"Accept", nil];
[MyRequest send];
RKResponse *Response = [MyRequest sendSynchronously];
return Response.bodyAsString; <--- looking to map this to translation object here
}
The snippet of your code seems a bit outdated. I strongly recommend reading the newest Object Mapping guide in order to leverage RestKit into it's fullest potential - especially the part Mapping without KVC.
Edit:
In order to post an object with RestKit and receive back an answer, we define a TranslationRequest class that will hold our request & Translation to hold our response.
Firstly, we set up our RKObjectManager and mappings (i usually do this in my AppDelegate):
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kOurBaseUrl];
[manager setSerializationMIMEType:RKMIMETypeJSON];
//this is a singleton, but we keep the manager variable to avoid using [RKObjectManager sharedManager] all the time
//Here we define a mapping for the request. Note: We define it as a mapping from JSON to entity and use inverseMapping selector later.
RKObjectMapping *translationRequestMapping = [RKObjectMapping mappingForClass:[TranslationRequest class]];
[translationRequestMapping mapKeyPath:#"RegionTag" toAttribute:#"regionTag"];
...
[[manager mappingProvider] setSerializationMapping:[translationRequestMapping inverseMapping] forClass:[TranslationRequest class]];
//now we define the mapping for our response object
RKObjectMapping *translationMapping = [RKObjectMapping mappingForClass:[Translation class]];
[translationMapping mapKeyPath:#"id" toAttribute:#"identifier"];
[translationMapping mapKeyPath:#"Translation" toAttribute:#"translation"];
[[manager mappingProvider] addObjectMapping:mapping];
//finally, we route our TranslationRequest class to a given endpoint
[[manager router] routeClass:[TranslationRequest class] toResourcePath:kMyPostEndpoint];
This should be enough of the necessary setup. We can call our backend anywhere in the code (e.g. in any controller) like this:
//we create new TranslationRequest
TranslationRequest *request = [[TranslationRequest alloc] init];
[request setRegionTag:#"Hello"];
....
//then we fetch the desired mapping to map our response with
RKObjectMapping *responseMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:class]
//and just call it. Be sure to let 'self' implement the required RKObjectManagerDelegate protocol
[[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self];]
Try this approach and let me know if you need any assistance.. I was not able to test it fully as i don't have any suitable backend that will return the responses, but judging from the RestKit log this should work.
You need to pass the returned JSON string into a JSON parser. I use SBJSON. You can then use the resulting dictionary to populate the properties of your object.
RestKit seems to have native objects that encapsulate four different JSON parsers. However, I'd advise caution because they seem to assume that the top level parsed object will always be a dictionary.
As another aside, the example in your question is not valid JSON. It should look like this:
{"id":"1","Translation":"Test"}

loadObjectsAtResourcePath (RestKit)

I have a method like this.
- (void)loadData {
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:#"http://localhost:8080/activiti-rest/service"];
[manager loadObjectsAtResourcePath:#"/process-definitions?start=0&size=10&sort=id&order=asc" objectClass:[Data class] delegate:self];
}
I get an error that says:
instance method '-loadObjectsAtResourcePath:objectClass:delegate' not found('return types default to 'id' ').
Can someone please help me how to call loadObjectsAtResourcePath function?
Maybe you want to define the mapping manually. Then just do something like this:
RKObjectMapping *mapping = [[[RKObjectManager sharedManager] mappingProvider] objectMappingForClass:[Data class]];
RKObjectLoader *loader = [[RKObjectManager sharedManager] loadObjectsAtResourcePath:#"/process-definitions?start=0&size=10&sort=id&order=asc" objectMapping:mapping delegate:self];
Don't forget to set base resource path to your RKObjectManager singleton.
I had to use the prototype that has objectMapping in it because i was trying to map the response to my own mapping called Data.
So i created an RKObjectMapping object ,configured to my own mapping class and then used this function.
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Data class]];
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:#"http://localhost:8080/activiti-rest/service"];
[manager loadObjectsAtResourcePath:#"/process-definitions?start=0&size=10&sort=id&order=asc" objectMapping:mapping delegate:self] ;
It worked!
Without knowing RestKit This sounds like a simple header problem. look at the header where "RKObjectManager" is defined. (Cmd click it in XCode to make sure it's available in your project.) Double check the method definition and make sure you're calling it correctly. Always use auto-complete to invoke methods.
Is your object/class implementing the in the interface?

RestKit: How does one post an array of objects?

Question summary:
Consider a class SyncObject that is KVC-compliant with properties such as: time, someValue, lastChange, uuid.
Consider an NSArray containing exclusively instances of SyncObject.
I need to submit the array to the server as a JSON array.
How would one submit this array to the server using HTTP POST using RestKit?
Example array:
[
{
"time": "14:45 10/21/2011",
"someValue": "15",
"lastChange": "14:45 10/21/2011",
"uuid": "0b07c510-f4c8-11e0-be50-0800200c9a66"
},
{
"time": "14:50 10/21/2011",
"someValue": "62",
"lastChange": "14:51 10/21/2011",
"uuid": "1a6d4480-f4c8-11e0-be50-0800200c9a66"
}
]
Details
I have an array of objects that I need to the server as JSON. It seems to me that RestKit is the easiest way to do this: I'm trying to avoid converting objects into a set of NSDictionary objects, and then using some JSON encoder to get JSON which I can POST to the server.
So, having created the array, and having set up the mapping for the class of objects stored in the array, I naturally try to POST to the server.
RKObjectManager* mgr = [RKObjectManager objectManagerWithBaseURL:#"http://localhost/someweb/api/"];
mgr.serializationMIMEType = RKMIMETypeFormURLEncoded;
mgr.client.username = #"username";
mgr.client.password = #"password";
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
[mapping mapKeyPath: #"time" toAttribute:#"time" ];
[mapping mapKeyPath: #"someValue" toAttribute:#"someValue" ];
[mapping mapKeyPath: #"lastChange" toAttribute:#"lastChange" ];
[mapping mapKeyPath: #"uuid" toAttribute:#"uuid" ];
RKObjectMapping* mappingForSerialization = [mapping inverseMapping];
[mgr.mappingProvider setSerializationMapping:mappingForSerialization
forClass:[NSManagedObject class]];
[mgr.router routeClass:[NSManagedObject class] toResourcePath:#"/sync" forMethod:RKRequestMethodPOST];
[mgr postObject:array delegate:nil/*self*/];
However, this is what I get out:
2011-10-11 14:57:51.769 AppConnect[1974:6e0b] *** Terminating app due to uncaught exception '(null)', reason: 'Unable to find a routable path for object of type '__NSArrayI' for HTTP Method 'POST''
Apparently, RestKit does not know how to handle NSArrays.
How does one post an array of objects using RestKit?
I've tried something different: I replaced the last line with a manual send through RKObjectLoader.
//[mgr postObject:[NSMutableDictionary dictionaryWithObject:array forKey:#"data"] delegate:nil/*self*/];
NSString* syncPath = #"/sync";
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];
//objectLoader.managedObjectStore = mgr.objectStore;
objectLoader.params = [NSDictionary dictionaryWithObject:array
forKey:#"MyData"];
[objectLoader send];
Unfortunately, this does not apply mapping of any sort, and instead transmits an array of objects' descriptions. Setting serializationMIMEType also does not affect the structure of transmitted contents, and params are always transmitted as application/x-www-form-urlencoded.
I also tried assigning serialization mapping and passing the object as targetObject and sourceObject (this seems to be what RestKit does internally in -[RKObjectManager postObject:delegate:]).
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];
//objectLoader.managedObjectStore = mgr.objectStore;
objectLoader.params = [NSMutableDictionary dictionaryWithObject:array
forKey:#"MyData"];
objectLoader.serializationMapping = mapping;
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.sourceObject = objectLoader.params;
objectLoader.targetObject = objectLoader.params;
[objectLoader send];
Unfortunately, no mapping occurs this way:
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.network:RKObjectLoader.m:290 POST or PUT request for source object {
MyData = (
"<NSManagedObject: 0x5935430> (entity: SomeRecord; id: 0x5934da0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p1> ; data: <fault>)",
"<NSManagedObject: 0x5935730> (entity: SomeRecord; id: 0x5934db0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p2> ; data: <fault>)"
);
}, serializing to MIME Type application/json for transport...
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:428 Starting mapping operation...
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'time'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'someValue'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'lastChange'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'uuid'
2011-10-12 12:36:48.145 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:448 Mapping operation did not find any mappable content
2011-10-12 12:36:48.146 MyProject[5119:207] T restkit.network:RKRequest.m:211 Prepared POST URLRequest '<NSMutableURLRequest http://someurl/api/sync?request=provide_key>'. HTTP Headers: {
Accept = "application/json";
"Content-Length" = 0;
}. HTTP Body: .
The restkit does not fund routable path for NSArray, because you defined your routing for NSManagedObject class. You probably want to create a custom class, say MySyncEntity that holds the ivars you define in your mapping. Then, you create your mapping like this:
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
....
[myManager setSerializationMIMEType:RKMIMETypeJSON];
[[myManager router] routeClass:[MySyncEntity class] toResourcePath:#"/sync"];
then you should be able to post your object to the API backend as JSON object.
Further clarification:
In this case, we want to post an array of NSManagedObject instances into a JSON based API. To do that we need to create a sync entity, that holds the objects in an array:
#interface MySyncEntity : NSObject {}
#property (nonatomic, retain) NSArray* mySyncArray;
...
#end
The mySyncArray will hold the payload we'd like to submit to the rest backend. Then, we create appropriate mapping for both NSManagedObject that will be sent in mySyncArray and the MySyncEntity entity itself.
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kBaseUrl];
...
RKObjectMapping *mngObjMapping = [RKObjectMapping mappingForClass:[NSManagedObject class]];
[mngObjMapping mapKeyPath: #"time" toAttribute:#"time"];
[mngObjMapping mapKeyPath: #"recordLevel" toAttribute:#"recordLevel"];
.... //map as many properties as you wish
[[manager mappingProvider] setSerializationMapping:[mngObjMapping inverseMapping]
forClass:[NSManagedObject class]];
//now, we create mapping for the MySyncEntity
RKObjectMapping *syncEntityMapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
[syncEntityMapping mapKeyPath:#"mySyncArray" toRelationship:#"mySyncArray" withMapping:mngObjMapping];
[[manager mappingProvider] setSerializationMapping:[syncEntityMapping inverseMapping]
forClass:[MySyncEntity class]];
Now with the mappings defined we can post the object to the server
[manager postObject:mySyncInstance delegate:nil];
The contents of mySyncInstance array will be mapped according to mngObjMapping and sent to defined rest endpoint.
As a further clarification, I'd like to point out that in mja's answer the key thing is
[syncEntityMapping mapKeyPath:#"mySyncArray" toRelationship:#"mySyncArray" withMapping:mngObjMapping];
This says "the mySyncArray keypath is an array which contains objects that should be mapped according to mngObjMapping".