解析苹果官方例子-tableview中图片懒加载

作者:Love@YR
链接:http://blog.csdn.net/jingqiu880905/article/details/51910417
请尊重原创,谢谢!

demo地址:
https://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009394

  1. app启动发送网络请求以拿到数据
 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:TopPaidAppsFeed]];

    // create an session data task to obtain and the XML feed
    NSURLSessionDataTask *sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:request                                                               completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)                                                                 {...                                                                                                                              ...}];
                                                                 [sessionTask resume];

其中completionHandler block里如果发现网络请求有误,就在主操作队列里弹出错误的弹框。

[[NSOperationQueue mainQueue] addOperationWithBlock:^{....}];

如果请求成功则进行下一步
2. 子线程里解析数据

self.queue = [[NSOperationQueue alloc] init];//重新生成一个队列
_parser = [[ParseOperation alloc] initWithData:data];//自定义一个操作,以网络请求完传入的nsdata作为输入,用NSXMLParser来解析,以appRecordList属性作为输出,重写其main方法
/*。。。。。设置解析这个操作的errorhandler和completionBlock(completionBlock这个属性是NSOperation本身就有的)。其中errorhandler和上面一样在主线程里弹错误提示框,completionBlock则在主线程里把拿到的数据(appRecordList)赋值给tableviewController,然后tableview reloadData*/

[self.queue addOperation:self.parser];//开始执行操作

接下来就是tableview的绘制工作
3. 关于RootViewController

  • heightForRowAtIndexPath:经实验证明此方法执行的次数为所有cell显示次数之和,重复滑动会执行很多次。所以这个方法里不要有大量的运算,最好直接缓存cell高度
  • 关于cell重用
     UITableViewCell *  cell=[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
//        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        if (!cell) {
//            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            NSLog(@"jean-----执行次数%d-----",m++);
        }
        cell.XXX=XXXXX;

中间那句alloc也可换成这样:

  cell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:nil options:nil] objectAtIndex:0];

官方说不带forIndexPath的 Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.说明只能拿到已经创建过的,所以需要考虑拿到为空时自己创建的事情。即需要多个判空的处理

而带forIndexPath的,则可以不要那句判空。
官方解释为 newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered,假定其已经注册过,如果未注册用此方法会引起崩溃。

实验证明:
带forindexpath:
1. 注册了cell,从来不为空,正常走
2. 没注册cell,走到dequeueReusableCellWithIdentifier这句就崩溃,所以也不用写if(!cell)了 已经崩了。

不带forindexpath:
1. 注册了cell,只创建了一个cell对象,不会走到if(!cell)里面因为cell对象存在,正常走
2. 没注册cell , 又没有在cell为空时alloc一个,return cell时崩溃说failed to obtain a cell from its dataSource
3. 没注册cell,在cell为空时alloc了一个,会alloc一屏的cell对象,比如此官方例子一屏能显示13行

注册方法:

//registerNib (比如viewcontroller的loadView,viewDidLoad中)
 [self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"CustomCellID”];

//代码注册,没有可视化界面,只需保证此处的ReuseIdentifier跟画cell时一致即可 (比如customTableView的initWithFrame:style:中)
  [self registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCellID"];

//storyboard注册,需要在对应的cell那里设置其ReuseIdentifier

PS:关于initWithStyle:reuseIdentifier方法和awakeFromNib方法
无xib,用registerClass方法注册,调用dequeueReusableCellWithIdentifier的时候会触发initWithStyle:reuseIdentifier方法而不会触发awakeFromNib
有xib,用registerNib方法注册,调用dequeueReusableCellWithIdentifier的时候会触发awakeFromNib方法而不会触发initWithStyle:reuseIdentifier
无xib,在storyboard里放置cell,所属为CustomCell类, 设置其reuseIdentifier,dequeueReusableCellWithIdentifier的时候会触发awakeFromNib方法而不会触发initWithStyle:reuseIdentifier

所以如果正在从nib/storyboard加载你的cell,initWithStyle不会被调用

  • 画cell的时候,发现如果此行的图片appIcon已经拿到了就直接显示,否则判断如果没有正在drag也没有正在减速即scroll已经停下来了 (if (self.tableView.dragging == NO && self.tableView.decelerating == NO))才去下载图片,否则就显示缺省图。
  • startDownload方法里下载完成在主线程里先把图片scale即缩放到要显示的大小之后再返回图片,以此来优化性能。然后再执行传过来的completionHandler()
  • 在tableview dealloc或者收到内存警告的时候去terminateAllDownloads。此方法让allDownloads数组里的object去执行方法即[allDownloads makeObjectsPerformSelector:@selector(cancelDownload)]; 再把数组remove掉。
  • scrollViewDidEndDragging:willDecelerate和scrollViewDidEndDecelerating方法里loadImagesForOnscreenRows,即拿到可视行,这些行的cell如果没图片就去下载。
  • entries是个数组,object是appRecord,当滚到的那行appRecord.appIcon图片为空就创建一个iconDownloader去下载,这样避免了下载完的又去下载。
  • imageDownloadsInProgress是个dictionary,key为indexPath,value为iconDownloader,iconDownloader持有appRecord。下载完成后对应的iconDownloader被从imageDownloadsInProgress里remove掉,加上if(iconDownloader==nil)时才去下载,这样就避免了正在下载(但未下载完成)的时候又发起一个同一行的下载任务。
  • 下载完iconDownloader.appRecord.appIcon被赋值,self.entries里相应的appRecord同时变化,所以不用担心[self.imageDownloadsInProgress removeObjectForKey:indexPath]之后即此iconDownloader被移除后会发生重复下载,因为判断是否需要下载用的是self.entries数组里的appRecord,而它的appIcon已经有了。
  • 由于上面所述,最后terminateAllDownloads 时候cancel的就是那些加入到下载队列中但没有下载完或者还没有下载的iconDownloader。
IconDownloader *iconDownloader = (self.imageDownloadsInProgress)[indexPath];
    if (iconDownloader == nil) //下载过的就为nil了就不会再下载
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{
            。。。。
            [self.imageDownloadsInProgress removeObjectForKey:indexPath];//下载完就把此iconDownloader remove掉

        }];
        (self.imageDownloadsInProgress)[indexPath] = iconDownloader;
        [iconDownloader startDownload];  
    }
在 iOS 开发TableView 是一个非常重要的视图控件,用于展示大量数据。而 TableView 的 HeaderView 和 FooterView 也是非常重要的组件,可以用于展示一些额外的信息或者操作按钮。在 TableView ,我们可以通过注册重用标识符来复用 Cell,但是对于 HeaderView 和 FooterView 却没有提供类似的注册方法。本文将介绍如何在 TableView 循环利用 HeaderView,并且还会介绍如何自定义 HeaderView。 ## 循环利用 TableView 的 HeaderView 在 TableView ,我们可以通过以下方法来设置 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)]; headerView.backgroundColor = [UIColor grayColor]; return headerView; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44; } ``` 上面的代码,我们通过实现 `tableView:viewForHeaderInSection:` 方法来设置 HeaderView 的内容和样式,通过实现 `tableView:heightForHeaderInSection:` 方法来设置 HeaderView 的高度。但是如果我们在 TableView 有很多组数据,每次都创建一个新的 HeaderView 会非常消耗性能,因此我们需要对 HeaderView 进行循环利用。 循环利用 HeaderView 的实现方法非常简单,我们只需要在 TableView 的代理方法通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法来获取 HeaderView,如果获取到的 HeaderView 为 nil,就创建一个新的 HeaderView,否则就返回重用的 HeaderView。 ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; if (!headerView) { headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerIdentifier]; headerView.contentView.backgroundColor = [UIColor grayColor]; } return headerView; } ``` 上面的代码,我们首先定义一个静态的重用标识符 `headerIdentifier`,然后通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法获取重用的 HeaderView。如果获取到的 HeaderView 为 nil,我们就创建一个新的 HeaderView,并且设置它的重用标识符为 `headerIdentifier`。最后,我们设置 HeaderView 的背景颜色,并且返回 HeaderView。 ## 自定义 TableView 的 HeaderView 除了循环利用 HeaderView,我们还可以自定义 HeaderView。自定义 HeaderView 的方法与自定义 Cell 的方法类似,我们需要在 XIB 或者代码创建一个自定义的 HeaderView,然后在 TableView 的代理方法返回它。 ### 在 XIB 创建自定义 HeaderView 在 XIB 创建自定义 HeaderView 的方法非常简单,我们只需要创建一个新的 XIB 文件,然后在 XIB 添加一个 UIView,将它的 Class 设置为 UITableViewHeaderFooterView,接着就可以在 XIB 自定义 HeaderView 的内容和样式了。 创建完成后,我们需要在代码注册这个 XIB 文件,并且设置它的重用标识符。在 TableView 的初始化方法,我们可以通过以下方法来注册 XIB 文件: ``` UINib *headerNib = [UINib nibWithNibName:@"HeaderView" bundle:nil]; [tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:@"headerIdentifier"]; ``` 上面的代码,我们首先通过 `nibWithNibName:bundle:` 方法加载 XIB 文件,然后通过 `registerNib:forHeaderFooterViewReuseIdentifier:` 方法注册 XIB 文件,并且设置它的重用标识符为 `headerIdentifier`。 最后,在 TableView 的代理方法,我们可以通过以下方法来获取自定义的 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; return headerView; } ``` ### 在代码创建自定义 HeaderView 在代码创建自定义 HeaderView 的方法也非常简单,我们只需要创建一个继承自 UITableViewHeaderFooterView 的类,然后在这个类实现自定义 HeaderView 的内容和样式。 ``` @interface CustomHeaderView : UITableViewHeaderFooterView @property (nonatomic, strong) UILabel *titleLabel; @end @implementation CustomHeaderView - (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithReuseIdentifier:reuseIdentifier]) { self.contentView.backgroundColor = [UIColor grayColor]; self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.contentView.bounds.size.width - 20, self.contentView.bounds.size.height)]; self.titleLabel.font = [UIFont systemFontOfSize:16]; self.titleLabel.textColor = [UIColor whiteColor]; [self.contentView addSubview:self.titleLabel]; } return self; } @end ``` 上面的代码,我们创建了一个名为 `CustomHeaderView` 的类,继承自 UITableViewHeaderFooterView。在这个类的初始化方法,我们设置了 HeaderView 的背景颜色,并且创建了一个 UILabel 来显示标题,最后将它添加到 HeaderView 的 contentView 上。 创建完成后,我们需要在代码注册这个自定义 HeaderView,并且设置它的重用标识符。在 TableView 的初始化方法,我们可以通过以下方法来注册自定义 HeaderView: ``` [tableView registerClass:[CustomHeaderView class] forHeaderFooterViewReuseIdentifier:@"headerIdentifier"]; ``` 上面的代码,我们通过 `registerClass:forHeaderFooterViewReuseIdentifier:` 方法注册自定义 HeaderView,并且设置它的重用标识符为 `headerIdentifier`。 最后,在 TableView 的代理方法,我们可以通过以下方法来获取自定义的 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; CustomHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; headerView.titleLabel.text = [NSString stringWithFormat:@"Header %ld", section]; return headerView; } ``` 上面的代码,我们首先定义一个静态的重用标识符 `headerIdentifier`,然后通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法获取自定义的 HeaderView,并且设置它的标题为 `Header section`。最后,我们返回自定义的 HeaderView。 总结 在本文,我们介绍了如何在 TableView 循环利用 HeaderView,并且还介绍了如何自定义 HeaderView。循环利用 HeaderView 可以提高 TableView 的性能,自定义 HeaderView 可以让我们更加灵活地控制 HeaderView 的样式和内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值