開發(fā)中,需要實(shí)現(xiàn)三個(gè)水平滑動(dòng)頁面,其中一個(gè)頁面是UITableView,頁面需要每個(gè)2秒刷新一次,另外兩個(gè)是普通UIView.
實(shí)現(xiàn)思路如下:三個(gè)頁面的水平滑動(dòng)用UICollectionView實(shí)現(xiàn),其中的UITabelView嵌套在UICollectionCell的contentView里面,其刷新用NSTimer來實(shí)現(xiàn).
下面是tableView中的代碼
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self timer];
}
return self;
}
- (void)dealloc{
[self.timer invalidate];
self.timer = nil;
}
- (NSTimer *)timer{
if (_timer == nil) {
_timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerDid) userInfo:nil repeats:YES];
}
return _timer;
}
- (void)timerDid{
[self reloadData];
NSLog(@"timer");
}
根據(jù)實(shí)際測(cè)試,當(dāng)在滑動(dòng)collectionView時(shí),并不會(huì)調(diào)用tableView的dealloc方法,并且控制臺(tái)一直打印timer的信息.也就是說timer對(duì)象和tableView對(duì)象并不會(huì)銷毀.這是因?yàn)閏ollectionView在滑動(dòng)時(shí)的重用機(jī)制造成的,放入緩存池中的collectionViewCell對(duì)象并沒有銷毀,也就不會(huì)調(diào)用dealloc方法,而timer執(zhí)行的方法又有對(duì)self的引用,所以tableView并沒有銷毀.當(dāng)用戶反復(fù)滑動(dòng)collectionView時(shí),會(huì)多次創(chuàng)建tableView,造成大量的資源浪費(fèi),降低手機(jī)性能.
解決方法,是在collectionView中的tableView頁面進(jìn)入緩存池后,手動(dòng)調(diào)用 [self.timer invalidate]方法,強(qiáng)行終止timer,collectionView中的方法如下
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
if (indexPath.row == 0) {
//將cell重用時(shí)的其他控件移除
[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
// cell.contentView.backgroundColor = [UIColor whiteColor];
ZDTabelView *tableView = [[ZDTabelView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
tableView.backgroundColor = [UIColor greenColor];
self.tableView = tableView;
[cell.contentView addSubview:tableView];
}else if(indexPath.row == 1){
[self.tableView.timer invalidate];
self.tableView.timer = nil;
[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
cell.contentView.backgroundColor = [UIColor grayColor];
}else{
[self.tableView.timer invalidate];
self.tableView.timer = nil;
[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
cell.contentView.backgroundColor = [UIColor redColor];
}
return cell;
}
Tips:在調(diào)用timer的invalidate方法后,timer有可能并沒有變成nil,所以需要顯式的指定.
下面是github上的Demo:
https://github.com/zhudong10/collectionViewWithTableView.git