Question

I'm trying to use RestKit to perform automatic mapping of any given entity class name, without having to define the fields manually.

Example, imagine a managed object called Product with fields: id, name, type. This entity is on the default store.

I need to get the list of products from this URL http://machin.net/products

RKEntityMapping *map = [RKEntityMapping mappingForEntityForName:@"Product"
    inManagedObjectStore:[RKManagedObjectStore defaultStore]];

Question 1 defaultStore is not satisfying the required store, I don't even know how to specify it.

[map addAttributeMappingsFromDictionary:@{
    @"id": @"id",
    @"name": @"name",
    @"type": @"type",
}];

Question 2 As you can see, I'm using all the fields and they are the same on source & destination, I didn't find any way to tell RestKit to simply use all the fields of the given class.

Was it helpful?

Solution 2

For 1. you need to configure your RestKit / Core Data stack

    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

    self.managedObjectStore = managedObjectStore;

    [RKManagedObjectStore setDefaultStore:managedObjectStore];

    // complete the core data stack setup
    [managedObjectStore createPersistentStoreCoordinator];

For 2. you can use

[map addAttributeMappingsFromArray:@[
@"id",
@"name",
@"type",
];

Technically you could use some introspection on the entity but you'd write a lot more code.

OTHER TIPS

About Question 2

I found a simple way to automatically map the entity by using RKPropertyIntrospector

NSEntityDescription *entity =
    [[managedObjectModel entitiesByName] objectForKey:@"Product"];
[map addAttributeMappingsFromArray:[[[RKPropertyInspector sharedInspector]
    propertyInspectionForEntity:entity] allKeys]];

We can even add exceptions by using @{} keysOfEntriesPassingTest

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top