Cell工厂主要使用的是:多态
举例说明:创建ViewController,放UITableView。创建继承UITableViewCell的BaseTableViewCell,创建BaseTableViewCell的3个子类,OneModelCell、TwoModelCell、ThreeModelCell。创建继承NSObject的BaseModel,创建BaseModel的3个子类,OneModel、TwoModel、ThreeModel。
数据如下:
UITableView的数据源方法中(此处省略基本步骤,记得设置属性)
@property (nonatomic, strong) UITableView *tableV; @property (nonatomic, strong) NSMutableArray *dataArr;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 根据indexPath.row获取我们对应的model BaseModel *model = self.dataArr[indexPath.row]; // 根据取出来的model获取对应的类名 NSString *modelName = [NSString stringWithUTF8String:object_getClassName(model)]; // 根据不同的唯一标示重用不同的cell BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:modelName]; // 如果cell不存在 if (cell == nil) { // 根据提供的model创建出对应的cell // 根据不同需求生产不同的产品 cell = [BaseTableViewCell initWithModel:model]; } [cell setBaseModel:model]; return cell; }
根据不同的标签区分不同的cell对应的model
这里是“tag”属性的值来区分,包括”Top News、 “imgextra”、 “music”1.在BaseModel中定义类的初始化方法
+ (instancetype)initWithDictionary:(NSDictionary *)dic;
// 根据字典中提供的数据分别创建出其对应的model来获取数据 + (instancetype)initWithDictionary:(NSDictionary *)dic { // 先使用当前类(父类)创建出model对象 BaseModel *model = nil; // 根据字典中key对应的数据初始化不同的子类对象并将其返回给我们的父类 if ([dic[@"tag"]isEqualToString:@"Top News"]) { model = [[OneModel alloc]init]; }else if([dic[@"tag"]isEqualToString:@"imgextra"]){ model = [[TwoModel alloc]init]; }else if([dic[@"tag"]isEqualToString:@"music"]){ model = [[ThreeModel alloc]init]; } [model setValuesForKeysWithDictionary:dic]; return model; } - (void)setValue:(id)value forUndefinedKey:(NSString *)key{ }
2.在OneModel、TwoModel、ThreeModel子类中写各自的属性
Cell的处理方法
一 在BaseTableViewCell中定义类的初始化方法,声明一个baseModel对象
// 根据不同类型的model创建不同的cell +(instancetype)initWithModel:(BaseModel *)model; // 在父类中声明一个baseModel对象,在其子类里重写set方法,在set方法内部去做赋值的操作 @property (nonatomic, strong) BaseModel *baseModel;
+ (instancetype)initWithModel:(BaseModel *)model { // 根据我们的OC函数获取model类名并将其转化为OC字符串 NSString *modelName = [NSString stringWithUTF8String:object_getClassName(model)]; // 使用model的类名拼接一个cell来获取我们的cell类名 NSString *cellName = [modelName stringByAppendingString:@"Cell"]; // 根据我们所提供的cellname来获取其对应的“cell子类”初始化一个cell对象返回给我们的父类对象 // 唯一标识可以使用我们所提供的model来给予不同cell所对应的标识来重用 BaseTableViewCell *cell = [[NSClassFromString(cellName) alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:modelName]; return cell; }
一 在OneModelCell、TwoModelCell、ThreeModelCell中重写初始化方法布局控件,并重写父类的setBaseModel方法。以OneModelCell为例。
- (void)setBaseModel:(BaseModel *)baseModel{ OneModel *model = (OneModel *)baseModel; self.titleLabel.text = model.title; [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]]; } - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { ....... } return self; }