您可能非常熟悉整个数组差异的概念,但这里有一个快速介绍。
假设我们在开发一个猫的 App。为了简化问题,让我们有这样一个 Cat
模型对象类
@interface Cat : NSObject
@property (nonatomic, readonly) NSString *uid;
@property (nonatomic, readonly) NSString *name;
+ (instancetype)catWithUid:(NSString *)uid name:(NSString *)name;
@end
在 App 中的某个地方,我们会有一个猫的列表,通常通过 UITableView
或 UICollectionView
来展示。一切都很顺利,直到我们需要动画更新。为了实现这一点,我们需要知道确切哪些项被删除、插入、更改或移动。这里是如何做到这一点的
NSArray<Cat *> *catsBefore = @[ ... ];
NSArray<Cat *> *catsAfter = @[ ... ];
NNSectionsDiffCalculator *diffCalculator = [[NNSectionsDiffCalculator alloc] init];
diffCalculator.objectIdBlock = ^(Cat *cat) {
return cat.uid;
};
NNSectionsDiff *diff = [diffCalculator calculateDiffForSingleSectionObjectsBefore:catsBefore andAfter:catsAfter];
// The diff object now contains all needed info about mutated indexPaths.
// The easiest way to apply it to UITableView or UICollectionView is a bunch of category methods:
[self.tableView reloadWithSectionsDiff:diff];
这就是全部!重新加载的过程非常可定制,并处理了可能导致崩溃的许多 UIKit 特性和问题。
您可以随时查看示例项目。希望很快会有更详细的指南 :)