Skip to content

Instantly share code, notes, and snippets.

@benvium
Created November 13, 2012 18:03
Show Gist options
  • Select an option

  • Save benvium/4067345 to your computer and use it in GitHub Desktop.

Select an option

Save benvium/4067345 to your computer and use it in GitHub Desktop.
RestKit object mapping when the root element is an array, and we use blocks
// e.g. server returns [ {name:"foo"}, {name:"bar} ]
_objectManager = [RKObjectManager managerWithBaseURLString:@"http://example.com/api"];
RKObjectMapping *rootMapping = [RKObjectMapping mappingForClass:[MyItem class]];
[rootMapping mapKeyPath:@"name" toAttribute:@"name"];
[_objectManager.mappingProvider addObjectMapping:rootMapping]; // note this just stores our instance..
/// LATER ON
RKObjectMapping* mapping = [_objectManager.mappingProvider objectMappingForClass:[MyItem class]];
[_objectManager loadObjectsAtResourcePath:path usingBlock:^(RKObjectLoader *loader) {
loader.objectMapping = mapping; // Here's the key. We're telling RestKit to use the MyItem mapping for the objects in the root.
loader.onDidLoadObjects = ^(NSArray* objects) {
for (NSObject* ob in objects) {
if ([ob isKindOfClass:[MyItem class]]) {
MyItem* device = (MyItem*)ob;
NSLog(@"Found MyItem %@", device.name);
} else {
NSLog(@"hmm.. got a %@", ob);
}
}
};
loader.onDidFailWithError = ^(NSError* error) {
// do something
};
loader.onDidFailLoadWithError = ^(NSError* error) {
// do something
};
}];
@benvium
Copy link
Copy Markdown
Author

benvium commented Nov 14, 2012

Starting out with restkit I found it pretty straightforward until I hit a rest command that returned an array. It seems restkit expects there to be a root level object e.g. { data: [ "a", "b", "c"] }. If your server doesn't do this you can't use the automatic mapping system. The solution is simple (manually tell the system which mapping to use) but I took me a while to figure out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment