RestKit/RestKit — Issue #398: Posting an array of mapped objects 
Author: ivucica
Created: 2011-10-12 14:28:33+00:00
State: open

Into an `RKObjectManager`, I'm adding a mapping for `MyClass`. I would like to use `RKObjectManager`'s `-postObject:delegate:` to submit an entire array of mapped objects.

Apparently, the closest I can get currently is:

* create a wrapper class `MyClassArray` containing just the array
* define a mapping for serializing this wrapper object
* map the array keypath to a relationship, passing along the mapping for `MyClass`
* post the `MyClassArray` object

This is what I have, after asking about this on StackOverflow.

@interface MyClassArray {
}
-(NSArray*)array;
@end
@implementation MyClassArray : NSObject
-(NSArray*)array {
return [NSArray arrayWithObjects:[MyClass myClass], nil];
}
@end

and then

RKObjectManager* mgr = [RKObjectManager objectManagerWithBaseURL:url];
mgr.serializationMIMEType = RKMIMETypeJSON;

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSManagedObject class]];
[mapping mapKeyPath: @"time" toAttribute:@"time" ];
[mapping mapKeyPath: @"someValue" toAttribute:@"someValue" ];
[mapping mapKeyPath: @"lastChange" toAttribute:@"lastChange" ];
[mapping mapKeyPath: @"uuid" toAttribute:@"uuid" ];
[mgr.mappingProvider setSerializationMapping:[mapping inverseMapping]
forClass:[MyClass class]];

RKObjectMapping * arrayMapping = [RKObjectMapping mappingForClass:[MyClassArray class]];
[arrayMapping mapKeyPath:@"array" toRelationship:@"array" withMapping:[mapping inverseMapping]];
[mgr.mappingProvider setSerializationMapping:[mapping inverseMapping]
forClass:[MyClassArray class]];

[mgr.router routeClass:[MyArrayClass class] toResourcePath:@"/sync" forMethod:RKRequestMethodPOST];

MyArrayClass * someObject = [[[MyArrayClass alloc] init] autorelease];
[mgr postObject:someObject delegate:nil];

This results in:

{ "blob" : [ { "lastChange" : "2011-10-11 11:53:14 +0000",
"recordValue" : 54796,
"time" : "2011-10-11 11:53:14 +0000",
"uuid" : "5DB0FA83-8BD2-4606-B9A0-630060EE3D0A"
},
{ "lastChange" : "2011-10-11 11:54:07 +0000",
"recordValue" : 2552,
"time" : "2011-10-11 11:54:07 +0000",
"uuid" : "2ABAECB7-B13A-4FEB-BA5C-A55C0C45C2B7"
}
] }

---

There should be a nice and easy way to post just the array:

[ { "lastChange" : "2011-10-11 11:53:14 +0000",
"recordValue" : 54796,
"time" : "2011-10-11 11:53:14 +0000",
"uuid" : "5DB0FA83-8BD2-4606-B9A0-630060EE3D0A"
},
{ "lastChange" : "2011-10-11 11:54:07 +0000",
"recordValue" : 2552,
"time" : "2011-10-11 11:54:07 +0000",
"uuid" : "2ABAECB7-B13A-4FEB-BA5C-A55C0C45C2B7"
}
]