NSOperation的使用
来源:互联网 发布:百度ar扫描软件 编辑:程序博客网 时间:2024/06/11 16:01
NSOperation的使用
请参照我的NSOperation Demo来看,这个demo实现的功能是使用NSOperationQueue后台下载图片,图片完成后刷新tableView。图片下载用的是NSURLSessionDownloadTask, 顺便复习了下NSURLSession,AFNetworking用多了都忘了API了!!!
完整的demo地址:https://github.com/dyljqq/NSOperationDemo
使用NSOperationQueue图片下载的代码如下:
//图片下载
- (void)downloadFavicon{ NSOperationQueue* queue = [[NSOperationQueue alloc] init]; int index = 0; //创建了四个后台线程 for (NSString* urlName in webSites) { [queue addOperationWithBlock:^{ NSString* urlString = [NSString stringWithFormat:@"http://%@/favicon.ico", urlName]; //详细的NSURLSession请自行google,或访问官方文档 NSURLRequest* request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]]; NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; NSURLSessionDownloadTask* task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error){ //获取返回的数据 NSData * data = [NSData dataWithContentsOfURL:location]; if (data != nil) { UIImage* image = [UIImage imageWithData:data]; if(image != nil){ //这里如果image为nil, 程序会crash,NSArray不允许有nil值 [webSitesIcon replaceObjectAtIndex:index withObject:image]; [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //图片下载完成后回到主线程刷新tableView [self.tableView reloadData]; }]; } } }]; [task resume]; }]; index++;}
}
0 0
- NSOperation的简单使用
- NSOperation的使用
- NSOperation的使用
- NSOperation的基本使用
- NSOperation的使用细节
- NSOperation多线程的使用
- NSOperation的使用
- NSOperation的使用
- NSOperation与NSOperationQuene的使用
- NSOperation和NSOperationQueue的使用
- NSOperation的介绍和使用
- NSOperation,NSOperationQueue基本的使用
- iOS多线程NSOperation的使用
- iOS-NSOperation 的使用(总结)
- 多线程:NSOperation 的基本使用
- 多线程:NSOperation 的依赖使用
- 多线程:NSOperation 的基本使用
- NSOperation的简单使用代码
- Android内存泄漏终极解决篇
- Smarty的初步使用
- 详解Dagger2
- Zox's code life 人生就是不停的战斗! xxx is not in the sudoers file.This incident will be reported.的解决方法
- Fragment切换与Activity状态丢失
- NSOperation的使用
- iOS UIView animation动画效果 (1)
- 第三周项目4:穷举法解决组合问题(5)委派任务
- 多线程--创建线程两种方式实例
- 尽量以const,enum,inline替换#define
- 最新的一些开源face alignment及评价
- 自制智能手机电话APP
- HDU-1003-Max Sum
- Java中ArrayList类的用法(转)