IGListKit框架解析(一)

IGListKit框架解析(一)

Instagram在2016年年底发布了基于数据驱动的UICollectionView框架IGListKit。使用数据驱动去创造更为快速灵活的列表控件。以下是该框架的特点:

  • 数据驱动(数据改变 -> Diff算法 -> update界面)
  • 可重复单元和组件的更好体系结构
  • 解耦的差异算法
  • 可以为数据模型自定义差异算法
  • 可扩展的API

IGListKit架构图

3637572-bd1b004bc054287f.png

IGListKit的管理者--IGListAdapter

如上图所示,该框架直接通过IGListAdapter对象去管理UICollectionView并封装了UICollectionViewDelegate、UICollectionViewDataSource的相关实现,同时Adapter和Controller互相持有,用户只需要实现IGListAdapterDataSource就可以实现一个灵活的列表。

IGListAdapter的三个参数:

  • IGListAdapterUpdater : 是一个实现了IGListUpdatingDelegate协议的对象,负责处理row和section的刷新。
  • Controller : Adapter和Controller互相持有的同时,也负责管理着SectionController。
  • WorkingRange : 可以为不可见范围的section准备内容。

IGListAdapter是如何管理UICollectionView的呢?

我们在和IGListAdapter中寻找和UICollectionViewDelegate、UICollectionViewDataSource相关的方法,发现在IGListAdapter+UICollectionView中有相关实现,以下是代码:

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.sectionMap.objects.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    IGListSectionController * sectionController = [self sectionControllerForSection:section];
    IGAssert(sectionController != nil, @"Nil section controller for section %zi for item %@. Check your -diffIdentifier and -isEqual: implementations.",
            section, [self.sectionMap objectForSection:section]);
    const NSInteger numberOfItems = [sectionController numberOfItems];
    IGAssert(numberOfItems >= 0, @"Cannot return negative number of items %zi for section controller %@.", numberOfItems, sectionController);
    return numberOfItems;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    IGListSectionController *sectionController = [self sectionControllerForSection:indexPath.section];

    // flag that a cell is being dequeued in case it tries to access a cell in the process
    _isDequeuingCell = YES;
    UICollectionViewCell *cell = [sectionController cellForItemAtIndex:indexPath.item];
    _isDequeuingCell = NO;

    IGAssert(cell != nil, @"Returned a nil cell at indexPath <%@> from section controller: <%@>", indexPath, sectionController);

    // associate the section controller with the cell so that we know which section controller is using it
    [self mapView:cell toSectionController:sectionController];

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    IGListSectionController *sectionController = [self sectionControllerForSection:indexPath.section];
    id <IGListSupplementaryViewSource> supplementarySource = [sectionController supplementaryViewSource];
    UICollectionReusableView *view = [supplementarySource viewForSupplementaryElementOfKind:kind atIndex:indexPath.item];
    IGAssert(view != nil, @"Returned a nil supplementary view at indexPath <%@> from section controller: <%@>, supplementary source: <%@>", indexPath, sectionController, supplementarySource);

    // associate the section controller with the cell so that we know which section controller is using it
    [self mapView:view toSectionController:sectionController];

    return view;
}

通过这段代码,我们可以清晰地看到IGListAdapter通过管理着IGListSectionController去实现UICollectionViewDelegate和UICollectionViewDataSource的相关实现,现在,我们去看看几个关键性的方法的实现去探索IGListAdapter的结构。

- (nullable IGListSectionController *)sectionControllerForSection:(NSInteger)section {
    IGAssertMainThread();
    
    return [self.sectionMap sectionControllerForSection:section];
}

- (NSInteger)sectionForSectionController:(IGListSectionController *)sectionController {
    IGAssertMainThread();
    IGParameterAssert(sectionController != nil);

    return [self.sectionMap sectionForSectionController:sectionController];
}

- (IGListSectionController *)sectionControllerForObject:(id)object {
    IGAssertMainThread();
    IGParameterAssert(object != nil);

    return [self.sectionMap sectionControllerForObject:object];
}

- (id)objectForSectionController:(IGListSectionController *)sectionController {
    IGAssertMainThread();
    IGParameterAssert(sectionController != nil);

    const NSInteger section = [self.sectionMap sectionForSectionController:sectionController];
    return [self.sectionMap objectForSection:section];
}

上述几个方法,都是IGListAdapter+UICollectionView中实现UICollectionViewDelegate、UICollectionViewDataSource时经常使用的方法,可以清晰地看到sectionMap是这些方法共同使用的属性,sectionMap是IGListKit中自定义的Map类型(IGListSectionMap),通过IGListSectionMap的代码,来一窥IGListAdapter实现管理者的方式。

@interface IGListSectionMap : NSObject <NSCopying>

- (instancetype)initWithMapTable:(NSMapTable *)mapTable NS_DESIGNATED_INITIALIZER;

/**
 The objects stored in the map.
 */
@property (nonatomic, strong, readonly) NSArray *objects;

/**
 Update the map with objects and the section controller counterparts.

 @param objects The objects in the collection.
 @param sectionControllers The section controllers that map to each object.
 */
- (void)updateWithObjects:(NSArray <id <NSObject>> *)objects sectionControllers:(NSArray <IGListSectionController *> *)sectionControllers;

/**
 Fetch a section controller given a section.

 @param section The section index of the section controller.

 @return A section controller.
 */
- (nullable IGListSectionController *)sectionControllerForSection:(NSInteger)section;

/**
 Fetch the object for a section

 @param section The section index of the object.

 @return The object corresponding to the section.
 */
- (nullable id)objectForSection:(NSInteger)section;

/**
 Fetch a section controller given an object. Can return nil.

 @param object The object that maps to a section controller.

 @return A section controller.
 */
- (nullable id)sectionControllerForObject:(id)object;

/**
 Look up the section index for a section controller.

 @param sectionController The list to look up.

 @return The section index of the given section controller if it exists, NSNotFound otherwise.
 */
- (NSInteger)sectionForSectionController:(id)sectionController;

/**
 Look up the section index for an object.

 @param object The object to look up.

 @return The section index of the given object if it exists, NSNotFound otherwise.
 */
- (NSInteger)sectionForObject:(id)object;

这是IGListSectionMap中主要的几个实现,也是经常用到的几个,我们再看看IGListSectionMap中的变量,很简单。

@interface IGListSectionMap ()

// both of these maps allow fast lookups of objects, list objects, and indexes
@property (nonatomic, strong, readonly, nonnull) NSMapTable<id, IGListSectionController *> *objectToSectionControllerMap;
@property (nonatomic, strong, readonly, nonnull) NSMapTable<IGListSectionController *, NSNumber *> *sectionControllerToSectionMap;

@property (nonatomic, strong, nonnull) NSMutableArray *mObjects;

@end

通过这两个变量的名称以及注释,也可以判断出该结构支持“双向查找”。再看看更新方法,确认一下是不是这么回事。

- (void)updateWithObjects:(NSArray *)objects sectionControllers:(NSArray *)sectionControllers {
    IGParameterAssert(objects.count == sectionControllers.count);

    [self reset];

    self.mObjects = [objects mutableCopy];

    id firstObject = objects.firstObject;
    id lastObject = objects.lastObject;

    [objects enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
        IGListSectionController *sectionController = sectionControllers[idx];

        // set the index of the list for easy reverse lookup
        [self.sectionControllerToSectionMap setObject:@(idx) forKey:sectionController];
        [self.objectToSectionControllerMap setObject:sectionController forKey:object];

        sectionController.isFirstSection = (object == firstObject);
        sectionController.isLastSection = (object == lastObject);
        sectionController.section = (NSInteger)idx;
    }];
}

由此可见,该结构是很灵活的,在IGListSectionMap结构的辅助下,IGListAdapter可以控制UICollectionView下层的IGListSectionController,通过IGListSectionController也通过IGListBindingSectionControllerDataSource去管理着UICollectionViewCell、ViewModel以及Cell的展示。

下一期,具体讲一下IGlistKit中运用的技巧、IGListBindingSectionController以及IGListKit的“灵魂”IGListDiff算法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270