Search code examples
iosobjective-carraysjsonrealm

Write NSArray object into Realm Data base - Objective C


I am creating a project using Realm. In this project, I am calling back end server and fetching JSON data. And I want to load the data to the Realm DB. I have successfully implemented the Realm and able to write data into it.

But I don't understand how to write NSArray object to Realm DB. I have followed some SO posts and wrote the below code.

RLM_ARRAY_TYPE(OBMDefinitionsModel)

@interface DefinitionsModel : RLMObject

@property (nonatomic) NSInteger defnitionID;
@property (nonatomic, strong) NSString *enTitle;
@property (nonatomic, strong) NSString *deTitle;

@end

#import <Realm/Realm.h>
#import "DefinitionsModel.h"

@interface DefinitionsRelationsModel : RLMObject

@property RLMArray<DefinitionsModel> *relationsArray;

@end

And below given the code for setting values for each object in JSONDataHandler class.

DefinitionsModel *defObj = [[DefinitionsModel alloc]init];
defObj.definitionID = [[defDic valueForKey:@"id"] integerValue];
defObj.enTitle = [[defDic objectForKey:@"title"] valueForKey:@"en"];
defObj.deTitle = [[defDic objectForKey:@"title"] valueForKey:@"de"];

But, how to set the value for relationsArray?

Please find below the sample JSON data;

{
    "id": 41,
    "title": {
        "de": "Technologien",
        "en": "Technologies"
    },
    "relations": [
        90,
        91,
        92,
        96
    ]
}

Please help. Thanks in advance.


Solution

  • You'd pass value into an array the same way you're already doing; you just need to loop through each array item and add it to Realm manually.

    for (NSNumber *relationID in defDic[@"relations"]) {
        DefinitionsModel *newModel = [[DefinitionsModel alloc] init];
        newModel.definitionID = relationID.integerValue;
        [myDefinitionsRelationModel.relationsArray addObject: newModel];
    }
    

    That being said, there are easier ways to parse JSON and insert the data into Realm. Patreon have released an open source library for this, for example.