#import "HomeTableViewController.h"
#import "CZApp.h"
@interface HomeTableViewController ()
//plist檔案資料的容器
@property(nonatomic,strong)NSArray *listArray;
//管理全域下載操作的隊列
@property(nonatomic,strong)NSOperationQueue *opQueue;
//所有下載操作的緩衝池
@property(nonatomic,strong)NSMutableDictionary *operationCache;
//所有映像的緩衝
@property(nonatomic,strong)NSMutableDictionary *imageCache;
@end
@implementation HomeTableViewController
//懶載入
-(NSArray *)listArray{
if (_listArray ==nil) {
NSString *path = [[NSBundlemainBundle]pathForResource:@"videos.plist"ofType:nil];
NSArray *dictArray = [NSArrayarrayWithContentsOfFile:path];
//字典轉模型
NSMutableArray *muArray = [[NSMutableArrayalloc]init];
for (NSDictionary *dictin dictArray) {
CZApp *app = [CZAppappWithDict:dict];
[muArray addObject:app];
}
_listArray = muArray;
}
return_listArray;
}
-(NSMutableDictionary *)operationCache{
if (_operationCache ==nil) {
_operationCache = [NSMutableDictionarydictionary];
}
return_operationCache;
}
-(NSMutableDictionary *)imageCache{
if (_imageCache ==nil) {
_imageCache = [[NSMutableDictionaryalloc]init];
}
return_imageCache;
}
-(NSOperationQueue *)opQueue{
if (_opQueue ==nil) {
_opQueue = [[NSOperationQueuealloc]init];
}
return_opQueue;
}
- (void)viewDidLoad {
[superviewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
returnself.listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
HomeTableViewCell *cell=[tableViewdequeueReusableCellWithIdentifier:@"cell"];
if (cell==nil) {
cell=[[HomeTableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@"cell"];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
CZApp *app =self.listArray[indexPath.row];
cell.label.text = app.video_title;
cell.detailLabel.text = app.video_subTitle;
//判斷圖片緩衝池中是否有圖片
if ([self.imageCacheobjectForKey:app.video_img]) {
NSLog(@"不用上網下載圖片,從圖片緩衝池中取");
cell.imageView.image =self.imageCache[app.video_img];
return cell;
}
//顯示佔位圖片
cell.dimageView.image = [UIImageimageNamed:@"user_default"];
//下載圖片(重構剪出去)
[selfdownloadimage:indexPath];
return cell;
}
-(void)downloadimage:(NSIndexPath *)indexPath{
CZApp *app =self.listArray[indexPath.row];
//判斷操作緩衝池中是否存在下載圖片的操作
if (self.operationCache[app.video_img]) {
NSLog(@"從緩衝池中玩命下載......");
return;
}
//多線程非同步
NSBlockOperation *downloadop = [NSBlockOperationblockOperationWithBlock:^{
NSLog(@"圖片下載中......");
//1.下載圖片
NSData *data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:app.video_img]];
UIImage *image = [UIImageimageWithData:data];
//2.將下載的圖片放在imageCache緩衝中
if (image) {
[self.imageCachesetObject:image forKey:app.video_img];
//將操作從緩衝池中移除
[self.operationCacheremoveObjectForKey:app.video_img];
}