1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| @interface ILAppsViewController () //存放数据 @property(nonatomic,strong) NSMutableArray *apps; //存放所有下载操作的队列 @property(nonatomic,strong) NSOperationQueue *queue; //存放所有的下载操作(url是key,operation是value) @property(nonatomic,strong) NSMutableDictionary *operations; @end
-(NSOperationQueue *)queue { if (!_queue) { self.queue=[[NSOperationQueue alloc]init]; } return _queue; } -(NSMutableDictionary *)operations { if (!_operations) { self.operations=[[NSMutableDictionary alloc]init]; } return _operations; }
- (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]; } //取出模型 App *app=self.apps[indexPath.row]; cell.textLabel.text=app.name; cell.detailTextLabel.text=app.download; //方法三 //取出当前图片url对应的下载操作(operation对象) NSBlockOperation *operation=self.operations[app.icon]; if (!operation) { NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{ NSURL *url=[NSURL URLWithString:app.icon]; NSData *data=[NSData dataWithContentsOfURL:url]; NSLog(@"正在下载图片----%@",url);
[[NSOperationQueue mainQueue]addOperationWithBlock:^{ cell.imageView.image=[UIImage imageWithData:data]; }]; }]; //添加操作到队列 [self.queue addOperation:operation]; //添加到字典中 self.operations[app.icon]=operation; } return cell; }
|