简体   繁体   中英

Parse Array from JSON to Realm

JSON:

"id": 13
"is_main": 1
"topic_id": 1
"images": [
   0: {
     "id": 188
     "title": "One
      }
   0: {
     "id": 192
     "title": "Two"
      }
   ]

So there is an Array with two Objects in JSON answer. My Realm model looks like:

@interface NewsRO : RLMObject

@property NSNumber <RLMInt> *newsID;
@property BOOL isMainNews;
@property NSNumber <RLMInt> *topicID;

@property NSArray *newsImages;
@property RLMArray <NewsImagesRO *><NewsImagesRO> *storedNewsImagesRO;

@end

And implementation:

#import "NewsRO.h"

@implementation NewsRO

+ (NSString *)primaryKey
{
    return @"newsID";
}

+ (NSArray<NSString *> *)ignoredProperties
{
    return @[@"newsImages"];
}

- (void)setNewsImages:(NSArray *)newsImages
{
    for (NSDictionary *dict in newsImages)
{
    dispatch_sync(dispatch_queue_create("checkCashedImage", 0), ^{
        NewsImagesRO *cashedObject = [NewsImagesRO objectForPrimaryKey:dict[[NKVHelper sharedInstance].kID]];
        if ( cashedObject == nil || [cashedObject.newsImagePath isEqual:dict[[NKVHelper sharedInstance].kImagePath]] == NO )
        {
            NewsImagesRO *newsImage = [[NewsImagesRO alloc]init];
            newsImage.newsImageID = dict[[NKVHelper sharedInstance].kID];
            newsImage.newsImagePath = dict[[NKVHelper sharedInstance].kImagePath];
            newsImage.newsImageTitle = dict[[NKVHelper sharedInstance].kImageTitle];
            newsImage.newsImageWidth = dict[[NKVHelper sharedInstance].kImageWidth];
            newsImage.newsImageHeight = dict[[NKVHelper sharedInstance].kImageHeight];
            [self.storedNewsImagesRO addObject:newsImage];
        }
    });
}
}

- (NSArray *)newsImages {
    return [self valueForKey:@"storedNewsImagesRO"];
}

@end

Questions:

1) How better parse JSON arrays to realm?

2) Should i check for cached value when i parse JSON by my way?

You can use some of the 3rd party frameworks for parsing JSON like ObjectMapper , see also https://github.com/realm/realm-cocoa/issues/694#issuecomment-144785299 for other frameworks.

And you can use -addOrUpdateObject: method for updating objects that have primary keys, see more info in docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM