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

来源:互联网 发布:网站数据库上传 编辑:程序博客网 时间:2024/04/29 09:49

作者: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];      }
2 0