(1)iOS7 — [UICollectionView _unhighlightAllItems],(2)Collection <__NSSetM: XXX> was mutated while being enumerated,(3)[NSIndexPath section] message sent to deallocated instance XXX

先上Crash堆栈信息:

Application Specific Information:
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSSetM: 0x16dab7a0> was mutated while being enumerated.'

Last Exception Backtrace:
0   CoreFoundation                  0x30a94f7e __exceptionPreprocess + 126
1   libobjc.A.dylib                 0x3b245cca objc_exception_throw + 34
2   CoreFoundation                  0x30a94a7c __NSFastEnumerationMutationHandler + 124
3   UIKit                           0x3381ed76 -[UICollectionView _unhighlightAllItems] + 126
4   UIKit                           0x334cc26e -[UICollectionView touchesBegan:withEvent:] + 362
5   UIKit                           0x332e662c -[UIWindow _sendTouchesForEvent:] + 316
6   UIKit                           0x332e16c6 -[UIWindow sendEvent:] + 754
7   UIKit                           0x332b68c8 -[UIApplication sendEvent:] + 192
8   UIKit                           0x332b4f72 _UIApplicationHandleEventQueue + 7098
9   CoreFoundation                  0x30a60206 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 10
10  CoreFoundation                  0x30a5f6d6 __CFRunLoopDoSources0 + 202
11  CoreFoundation                  0x30a5deca __CFRunLoopRun + 618
12  CoreFoundation                  0x309c8eba CFRunLoopRunSpecific + 518
13  CoreFoundation                  0x309c8c9e CFRunLoopRunInMode + 102
14  GraphicsServices                0x358ce65e GSEventRunModal + 134
15  UIKit                           0x33315148 UIApplicationMain + 1132
16  MyAppName                       0x00af441a main (main.m:14)
17  libdyld.dylib                   0x3b752ab2 tlv_initializer + 2
1、原因如下:

iOS7系统,滑动CollectionView的同时reloadData。

2、解决方案:

(1)对于只有1个section的UICollectionView,使用reloadSections代替reloadData,代码如下:

    [UIView setAnimationsEnabled:animated];
    [collectionView performBatchUpdates:^{
        [collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    } completion:^(BOOL finished) {
        [UIView setAnimationsEnabled:YES];
    }];

(2)对于有多个section的UICollectionView,则可以使用insertSections来替换reloadData,例如类似这样的代码:

    self.totalSections++;
    [self.mCollectionView performBatchUpdates:^{
        [self.mCollectionView insertSections:[NSIndexSet indexSetWithIndex:self.totalSections-1]];
    } completion:^(BOOL finished) {
        ...
    }];
3、如果读者有兴趣,可以阅读以下的分析过程:

显然,该堆栈为全系统栈,没有捕获到App的任何代码,极大的增加了排查问题的范围和难度,但比较幸运的是,堆栈信息给出了错误原因:Collection <__NSSetM: 0x16dab7a0> was mutated while being enumerated。复制粘贴,谷歌一下,大部分网友给出的原因是:在遍历集合的同时,对集合中的元素做了增删改操作。类似于如下代码:

for (NSString *obj in self.testArray) {
    ...
    [self.testArray addObject:@"4"];
    ...
}

但是,如果项目中真有这样的代码,在开发调试的时候就应该很容易暴露问题,不至于到线上才出现。那有没有可能是多线程操作导致的呢?类似于如下代码:

// 主线程
for (NSString *obj in self.testArray) {
    ...
}
    
// 子线程
[self.testArray addObject:@"4"];

顺着这个思路,开始查找代码中是否有多线程使用NSMutableSet的地方,经过一番辛苦的代码走查,并没有发现这样的逻辑代码,于是有点怀疑这个<__NSSetM: 0x16dab7a0>并不是App代码创建的对象,而是系统框架内部创建的,那具体是哪个类呢?目前看来,只能从全系统栈中寻找答案了。

从上往下逐行分析,发现与UICollectionView相关,谷歌一下:[UICollectionView _unhighlightAllItems],结果显示,遇到此问题的人不止我一个,在Stack Overflow有高人给出了Crash复现路径、原因猜测分析、以及问题解决方案:
(1)复现路径:calling reloadData while the user is dragging the collection view.
(2)猜测分析:My guess is that there is a weak reference to the highlighted cell's indexPath somewhere inside of the collectionView, and that calling reload will dealloc that indexPath. When the collectionView then tries to unhighlight the cell, it crashes.
(3)解决方案:使用reloadSections代替reloadData。

为了验证这3点,尤其是(1)和(3),以确保问题从根本上得到解决,我做了一个demo,关键代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.totalItems = 5;
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testForCrash) userInfo:nil repeats:YES];
}

- (void)testForCrash {
    self.totalItems++;
    [self.cv_test reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.totalItems;
}

开一个定时器,间隔1秒钟增加1个item,并且reloadData。这这个过程中,频繁滑动CollectionView,用不了很久,就会出现Crash:[NSIndexPath section] message sent to deallocated instance XXX(前提是开启了Zombie Objects调试选项)。很显然,访问了一个已释放的对象,并且从跟踪的异常堆栈来看,是在遍历NSMutableOrderedSet时发生了Crash,再结合Collection <__NSSetM: XXX> was mutated while being enumerated原因,可以确定这个<__NSSetM: XXX>是UICollectionView内部的一个NSMutableOrderedSet对象。

(1)iOS7 — [UICollectionView _unhighlightAllItems],(2)Collection <__NSSetM: XXX> was mutated while being enumerated,(3)[NSIndexPath section] message sent to deallocated instance XXX_第1张图片
Crash.png

注意:要复现这个Crash,必须在iOS7设备上运行。据我不完全统计,线上的这个问题都只出现在iOS7系统上,其他系统(8,9,10)并没有发现这个问题,并且我在iOS10的设备上运行这个Demo,相同的操作并没有复现这个Crash。有兴趣的同学可以在8和9的系统上测试验证,由此可以猜测这个属于iOS7系统特有的问题。

由于iOS并没有开放UICollectionView的源码,对于第2点在此不做任何分析,以免误导读者,其实我也不懂。

关于第3点提到的解决方案,亲测可行。至于稳定性如何,还得时间来验证。但这里想补充一点的是,如果这个UICollectionView有多个section,则可以使用insertSections来替换reloadData,例如类似这样的代码:

self.totalSections++;
[self.mCollectionView performBatchUpdates:^{
    [self.mCollectionView insertSections:[NSIndexSet indexSetWithIndex:self.totalSections-1]];
} completion:^(BOOL finished) {
    ...
}];

再次说明:这个问题只有在iOS7的系统上才出现,也就是说,对于7之后的系统还是可以放心使用reloadData。

全文完。

你可能感兴趣的:((1)iOS7 — [UICollectionView _unhighlightAllItems],(2)Collection <__NSSetM: XXX> was mutated while being enumerated,(3)[NSIndexPath section] message sent to deallocated instance XXX)