Insert value from Mantle model to RealmDB

77 views Asked by At

I have an issue: How can I save value from Mantle model to Realm database with a loop? my code below:

MTLmodel *model = [MTLJSONAdapter modelOfClass:[MTLmodel class] fromJSONDictionary:jsonResponse error:&error];

FreefoodRealmdb* food = [[FreefoodRealmdb alloc]init];
food.foodName    =  model.name;

NSLog(@"%@",food.foodName);

RLMRealm *realm = [RLMRealm defaultRealm];

[realm beginWriteTransaction];
[realm addObject:food];
[realm commitWriteTransaction];

This save only first element of the model but I need to save all of them together. How can I do that??

Many thanks in advance!!

1

There are 1 answers

0
TiM On

Since Mantle also requires your model objects be subclassed from a template class, it's not possible to have a single object composed of both MTLModel and RLMObject classes.

As such, it's necessary to manually copy the values from your Mantle object to a Realm object in order to save it.

If your Mantle object property names match the names in Realm, you might be able to automate the process to a fair degree:

NSDictionary *mantleDict = model.dictionaryValue;
FreeFood *freeFood = [[FreeFood alloc] init]; 

for (RLMProperty *property in freeFood.objectSchema.properties) {
    freeFood[property.name] = mantleDict[propertyName];
}

RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
    [realm addObject:food];
}];

For cleanliness, you could also move this 'copy' logic to a init method of your Realm Object

FreeFood *freeFood = [[FreeFood alloc] initWithMantleModel:model];