小算法 数组分组 三个一堆

2021-12-09  本文已影响0人  木子李55

今天碰到一个需求,如下图,接口返回的是一个列表,需要移动端每三个做一页,


效果图

这就需要对列表进行处理,每三个放一堆,重新放到一个数组里,然后cell里放个tableview,用新数据赋值即可。

    /*
    处理前:
    @[@"", @"", @"", @"", @"", @"", @"", @"", @""];
    处理后:
    @[@[@"", @"", @""], @[@"", @"", @""], @[@"", @"", @""]];
     */

    //** 创建处理前的数据
    NSMutableArray *oldList = [NSMutableArray array];
    for (int i = 0; i < 20; i++) {
        [oldList addObject:[NSString stringWithFormat:@"hh-%d", i]];
    }
    NSLog(@"原始数据 %@", oldList);

    // 处理数据
    NSMutableArray *newList = [NSMutableArray array];
    NSMutableArray *tep = [NSMutableArray array];
    for (int i = 0; i < oldList.count; i++) {

        [tep addObject:oldList[i]];

        // 如果遍历完了,最后一次的可能不满也送走
        if (i == oldList.count-1) {
            [newList addObject:tep.mutableCopy];
            [tep removeAllObjects];
        }
        // 加满三个就送走
        if (tep.count == 3) {
            [newList addObject:tep.mutableCopy];
            [tep removeAllObjects];
        }
    }

    NSLog(@"处理后的数据 %@", newList);

上一篇 下一篇

猜你喜欢

热点阅读