【问题标题】:Dynamic model cascading based on property with JSONModel基于 JSONModel 属性的动态模型级联
【发布时间】:2015-07-30 09:19:01
【问题描述】:

给定以下 JSON blob:

[
  {
    type: "audio",
    title: "Audio example title",
  },
  {
    type: "video",
    title: "Video example title",
  },
  {
    type: "audio",
    title: "Another audio example title",
  },
]

和两个 JSONModel 模型类(AudioModel、VideoModel)。是否可以让 JSONModel 在将 JSON 映射到模型时根据 type 属性自动创建其中一个模型类?

【问题讨论】:

标签: ios objective-c jsonmodel


【解决方案1】:

可以使用for..in 循环并检查类型属性并根据下面的类型创建模型对象

NSMutableArray *audioModelArray = [NSMutableArray alloc] init];
NSMutableArray *videoModelArray = [NSMutableArray alloc] init];

    for(NSdictionary *jsonDict in jsonArray) {
        if(jsonDict[@"type"] isEqualToString:@"audio") {
             AudioModel *audio  = [AudioModel alloc]initWithTitle:jsonDict[@"title"]]; 
            [audioModelArray addObject: audio];
        } else {
          VideoModel *audio  = [VideoModel alloc]  initWithTitle:jsonDict[@"title"]];
         [videoModelArray addObject: audio];
        }
    }

然后您可以迭代 audioModelArrayvideoModelArray 对象以访问 audoModel 和 videoModel 对象及其属性。

【讨论】:

    【解决方案2】:

    JSONModel 贡献者之间围绕这个问题进行了相当多的讨论。结论似乎是实现自己的类集群是最好的选择。

    如何执行此操作的示例 - 复制自 my comment on the GitHub issue

    + (Class)subclassForType:(NSInteger)pipeType
    {
        switch (pipeType)
        {
            case 1: return MyClassOne.class;
            case 2: return MyClassTwo.class;
        }
    
        return nil;
    }
    
    // JSONModel calls this
    - (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)error
    {
        if ([self isExclusiveSubclass])
            return [super initWithDictionary:dict error:error];
    
        self = nil;
    
        NSInteger type = [dict[@"type"] integerValue];
        Class class = [MyClass subclassForType:type];
    
        return [[class alloc] initWithDictionary:dict error:error];
    }
    
    // returns true if class is a subclass of MyClass (false if class is MyClass)
    - (BOOL)isExclusiveSubclass
    {
        if (![self isKindOfClass:MyClass.class])
            return false;
    
        if ([self isMemberOfClass:MyClass.class])
            return false;
    
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2014-01-07
      • 2016-07-21
      • 1970-01-01
      相关资源
      最近更新 更多