iOS多线程应用开发中自定义NSOperation类的实例解析

2020-01-14 18:41:39于丽

    cell.textLabel.text=app.name;
    cell.detailTextLabel.text=app.download;
    
    //下载图片数据
//    NSLog(@"加载图片数据---%@", [NSThread currentThread]);
//    NSURL *url=[NSURL URLWithString:app.icon];
//    NSData *data=[NSData dataWithContentsOfURL:url];
//    UIImage *imgae=[UIImage imageWithData:data];
//    cell.imageView.image=imgae;
    
    //创建一个OPeration对象
    YYdownLoadOperation *operation=[[YYdownLoadOperation alloc]init];
    operation.url=app.icon;
    operation.indexPath=indexPath;
    operation.delegate=self;
    
    //把操作对象添加到队列中在去
    [self.queue addOperation:operation];

//    NSLog(@"完成显示");
    return cell;
}
-(void)downLoadOperation:(YYdownLoadOperation *)operation didFishedDownLoad:(UIImage *)image
{
    //返回图片数据给每行对应的cell的imageview.image
    //取出tableview中indexPath这一行对应的cell
    UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:operation.indexPath];
    //显示图片
    cell.imageView.image=image;
//    NSLog(@"cell--index--%@---%@",operation.indexPath,[NSThread currentThread]);
    //一定要刷新表格
    [self.tableView reloadData];
    NSLog(@"--%@--",[NSThread currentThread]);

}
@end


说明:通过打印可以发现上面的代码存在很大的问题。

 

问题1:需要保证一个url对应一个operation对象。

问题2:下载完需要移除。移除执行完毕的操作。

问题3:保证一个url对应一个image。
下面对主控制器中得代码进行改进:

复制代码
//
//  YYViewController.m
//  01-自定义Operation
//
//  Created by apple on 14-6-26.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

 

#import "YYViewController.h"