DSDataSource.m 2.1 KB
//
//  DSDataSource.m
//  DreamSleep
//
//  Created by peter on 2022/4/8.
//

#import "DSDataSource.h"

@interface DSDataSource ()
/** 是否是section */
@property NSInteger isSection;
@end

@implementation DSDataSource

- (id)initWithIdentifier:(NSString *)identifier datas:(NSArray *)datas isSection:(BOOL)isSection configureBlock:(CellConfigureBlock)cellBlock {
    if (self = [super init]) {
        _cellIdentifier = identifier;
        _dataArray = [NSMutableArray arrayWithArray:datas];
        _isSection = isSection;
        _cellConfigureBlock = [cellBlock copy];
    }
    return self;
}

- (void)addDataArray:(NSArray *)datas {
    if(!datas) { return; }
    
    if (self.dataArray.count > 0) { [self.dataArray removeAllObjects]; }
    
    [self.dataArray addObjectsFromArray:datas];
}

- (id)modelAtIndexPath:(NSIndexPath *)indexPath {
    // 需要判断是否是row还是section
    if (self.isSection) {
        return self.dataArray.count > indexPath.section ? self.dataArray[indexPath.section] : nil;
    } else {
        return self.dataArray.count > indexPath.row ? self.dataArray[indexPath.row] : nil;
    }
}

#pragma mark - UITableViewDataSource
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell *cell = self.cellIdentifier ? [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath] :
    [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    id model = [self modelAtIndexPath:indexPath];
    if (self.cellConfigureBlock) {
        self.cellConfigureBlock(cell, model, indexPath);
    }
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isSection) {
        return !self.dataArray ? 1 : self.dataArray.count;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isSection) {
        return 1;
    } else {
        return !self.dataArray ? 1 : self.dataArray.count;
    }
}

@end