2016-06-30 4 views
3

JSON:Анализировать массив из JSON в Realm

"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 по-моему?

ответ

1

Вы можете использовать некоторые сторонние рамки для разбора JSON, например ObjectMapper, см. Также https://github.com/realm/realm-cocoa/issues/694#issuecomment-144785299 для других фреймворков.

И вы можете использовать метод -addOrUpdateObject: для обновления объектов с первичными ключами, см. Дополнительную информацию в docs.

Смежные вопросы