【问题标题】:Parse Array from JSON to Realm将数组从 JSON 解析到 Realm
【发布时间】:2016-06-30 11:23:44
【问题描述】:

JSON:

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

所以在 JSON 答案中有一个包含两个对象的数组。我的 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 时是否应该检查缓存值?

【问题讨论】:

    标签: ios json realm


    【解决方案1】:

    您可以使用一些第 3 方框架来解析 JSON,例如 ObjectMapper,另请参阅 https://github.com/realm/realm-cocoa/issues/694#issuecomment-144785299 了解其他框架。

    您可以使用-addOrUpdateObject: 方法更新具有主键的对象,请参阅docs 中的更多信息。

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多