簡體   English   中英

從JSON到Realm解析數組

[英]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"
      }
   ]

所以在JSON答案中有一個帶有兩個對象的數組。 My Realm模型看起來像:

@interface NewsRO : RLMObject

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

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

@end

並實施:

#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

問題:

1)如何更好地解析JSON數組到領域?

2)當我按自己的方式解析JSON時,我應該檢查緩存的值嗎?

您可以使用某些第三方框架來解析像ObjectMapper這樣的JSON,另請參閱https://github.com/realm/realm-cocoa/issues/694#issuecomment-144785299以了解其他框架。

您可以使用-addOrUpdateObject:方法更新具有主鍵的對象,請參閱docs中的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM