Created
November 13, 2012 18:03
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 | |
| }; | |
| }]; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!