cell简单工厂模式

MVC模式:

model:创建一个baseModel,创建其他子类对象

//根据传过来的数据源(字典)判断,并且进行对应Model映射
+ (instancetype)modelWithDictionary:(NSDictionary *)dict
{
    BaseModel * model = nil;
    if ([dict[@"tag"] isEqualToString:@"Top News"]) {
        model = [OneModel new];
    }else if ([dict[@"tag"] isEqualToString:@"imgextra"]) {
        model = [TwoModel new];
        
    }else if ([dict[@"tag"] isEqualToString:@"music"]) {
        model = [ThreeModel new];
    }else {
        
    }
    
    //字典对Model赋值
    [model setValuesForKeysWithDictionary:dict];
    
    return model;
}
cell:创建BaseCell类,创建其他子类对象

+(instancetype)cellWithModel:(BaseModel *)model
{
    //获取Model的名字
    NSString * modelName = [NSString stringWithUTF8String:object_getClassName(model)];
    //根据Model的名字拼接cell获取Cell类名
    NSString * cellName = [NSString stringWithFormat:@"%@Cell",modelName];
    
    //通过类名获取对象并且创建
    BaseCell * cell = [[objc_getClass(cellName.UTF8String) alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:modelName];
    
    return cell;
}
controller里:

可以直接使用basecell指向所有cell的子类对象

原文地址:https://www.cnblogs.com/xiangrikui/p/5251463.html