昨天介绍了NSThread方法的使用,今天介绍 NSOpreation的网络下载。
小的知识点我决定用简洁的方式呈现,以便于查阅。
1.用过选择器进行 NSOpreation的网络加载
1)定义NSInvocationOperation对象。
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downLoadImgae:) object:indexPath];
设置到线程队列中
[self.queue addOperation:operation];
2)downLoadImgage方法
- (void)downLoadImgae:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSString *str = [self.array objectAtIndex:row];
NSURL *url = [NSURL URLWithString:str];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
LCMyIndetifiterCell *cell = (LCMyIndetifiterCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = image;
[cell.activityIndicatorView stopAnimating];
[cell.activityIndicatorView setHidesWhenStopped:YES];
//[self.tableView reloadData];
}
[self.queue addOperationWithBlock:^(void){
NSInteger row = [indexPath row];
NSString *str = [self.array objectAtIndex:row];
NSURL *url = [NSURL URLWithString:str];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
cell.imageView.image = image;
[cell.activityIndicatorView stopAnimating];
[cell.activityIndicatorView setHidesWhenStopped:YES];
效果如下:
在主线程中更新 ,发现效果不是很理想
- (void)downLoadImgae:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSString *str = [self.array objectAtIndex:row];
NSURL *url = [NSURL URLWithString:str];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
// LCMyIndetifiterCell *cell = (LCMyIndetifiterCell *)[self.tableView cellForRowAtIndexPath:indexPath];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:indexPath,@"indexpath",image,@"image", nil];
[self performSelectorOnMainThread:@selector(updateUI:) withObject:userInfo waitUntilDone:NO];
// cell.imageView.image = image;
//[self.tableView reloadData];
}
- (void)updateUI:(id)sender
{
NSDictionary *userInfo = sender;
NSIndexPath *indexPath = [userInfo objectForKey:@"indepath"];
UIImage *image = [userInfo objectForKey:@"image"];
LCMyIndetifiterCell *cell = (LCMyIndetifiterCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = image;
[cell.activityIndicatorView stopAnimating];
[cell.activityIndicatorView setHidesWhenStopped:YES];
}