@property (nonatomic , copy) NSString *name;
@property (nonatomic , copy) NSString *download;
@property (nonatomic , copy) NSString *icon;
+ (instancetype)appWithDict:(NSDictionary *)dict;
+ (instancetype)appWithDict:(NSDictionary *)dict {
LMApp *app = [[self alloc] init];
[app setValuesForKeysWithDictionary:dict];
return app;
}
@property (nonatomic , strong ) NSMutableArray *apps;
@property (nonatomic , strong ) NSOperationQueue *queue;
@property (nonatomic , strong ) NSMutableDictionary *operations;
@property (nonatomic , strong ) NSMutableDictionary *images;
@end
@implementation LMTableViewController
#pragma mark 懒加载
- (NSMutableArray *)apps {
if (!_apps) {
NSString *file = [[NSBundle mainBundle] pathForResource:@"apps" ofType:@"plist" ];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
NSMutableArray *appArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
LMApp *app = [LMApp appWithDict:dict];
[appArray addObject:app];
}
self .apps = appArray;
}
return _apps;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"app" ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
LMApp *app = self .apps [indexPath.row ];
cell.textLabel .text = app.name ;
cell.detailTextLabel .text = app.download ;
UIImage *image = self .images [app.icon ];
if (image) {
cell.imageView .image = image;
} else {
cell.imageView .image = [UIImage imageNamed:@"placeholder" ];
#warning 下载图片
[self download:app.icon indexpath:indexPath];
}
return cell;
}
- (void )download:(NSString *)imageUrl indexpath:(NSIndexPath *)indexPath {
NSBlockOperation *operation = self .operations [imageUrl];
if (operation) return ;
__weak typeof(self ) appVc = self ;
operation = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if (image) {
appVc.images [imageUrl] = image;
}
[appVc.operations removeObjectForKey:imageUrl];
[appVc.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}];
}];
[self .queue addOperation:operation];
self .operations [imageUrl] = operation;
}
- (void )didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[self .queue cancelAllOperations];
[self .operations removeAllObjects];
[self .images removeAllObjects];
}
- (void )scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self .queue setSuspended:YES ];
}
- (void )scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self .queue setSuspended:NO ];
}