23&24day 网络、cell的代码块,以及常见错误
来源:互联网 发布:ubuntu l2tp 编辑:程序博客网 时间:2024/05/19 23:10
代码块
一、NSOperation
-cell的图片下载,防止图片重复下载
/** 存储下载图片的operation操作,保证一个URL对应一个操作*/@property (nonatomic,strong) NSMutableDictionary *operations; if (model.iconImage) { [cell.imageView setImage:model.iconImage]; }else{ //下载图片 //获取operation NSBlockOperation *operation = self.operations[model.icon]; // HSWS(weakself); if (operation == nil) { //创建operation operation = [NSBlockOperation blockOperationWithBlock:^{ //下载图片 NSURL *url = [NSURL URLWithString:model.icon]; UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]]; [model setIconImage:image]; NSLog(@"%@",url); //回到主线程进行cell的刷新 [[NSOperationQueue mainQueue]addOperationWithBlock:^{ //显示cell [cell.imageView setImage:image]; }]; }]; //添加到队列--第一次创建operation才添加,保证一个URL对应的operation只执行一次 [self.queue addOperation:operation]; //添加到operations self.operations[model.icon]= operation; } }
cell的图片下载-代码完善
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //获取模型 HSAppsModel *model = self.dataList[indexPath.row]; NSString *indetifier = @"UITableViewCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indetifier]; if (nil == cell) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:indetifier]; } //设置cell [cell.textLabel setText:model.name]; [cell.detailTextLabel setText:model.download]; if (self.images[model.icon]) {//已经存在图片 [cell.imageView setImage:self.images[model.icon]]; }else{ //说明未下载图片(未缓存过) //设置占位图片 [cell.imageView setImage:[UIImage imageNamed:@"placeholder.jpg"]];//清除cell的图片--cell重用 设置下载过程的默认图片 [self downloadWithUrl:model.icon indexPath:indexPath]; } return cell;}#pragma mark - 下载图片- (void)downloadWithUrl:(NSString*)url indexPath:(NSIndexPath*)indexPath{ //获取operation NSBlockOperation *operation = self.operations[url]; HSWS(weakself); if (operation) {//正在下载中 return; } //创建operation operation = [NSBlockOperation blockOperationWithBlock:^{ [NSThread sleepForTimeInterval:5]; NSURL *nsurl = [NSURL URLWithString:url]; //下载图片 UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:nsurl]]; //缓存图片 if (image) {//字典不允许存放nil对象 weakself.images[url] = image; } //回到主线程进行cell的刷新 [[NSOperationQueue mainQueue]addOperationWithBlock:^{ //从字典中移除下载操作--代表下载完成 保证一个URL对应的operation只执行一次 [weakself.operations removeObjectForKey:url]; //只要设置到正确的位置(row),而直接操作cell--因为cell会被重复利用 // [cell.imageView setImage:image]; // [tableView reloadData]; [weakself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; }]; }]; //执行下载操作 [self.queue addOperation:operation]; //添加到operations--防止重复下载 self.operations[url]= operation;}#pragma mark -scrollView Delegate- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ //暂停队列 [self.queue setSuspended:YES];}- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{ //恢复队列 [self.queue setSuspended:NO];}/**内存处理*/- (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; [self.images removeAllObjects]; [self.operations removeAllObjects]; [self.queue cancelAllOperations];}
03.自定义operation
自动以operation的注意事项
cell的图片下载04-自定义Operation/** 自定义operation的注意点 1.如果是异步操作,无法访问主线程的自动释放池 2、经常检测操作是否被取消 */- (void)main{ @autoreleasepool {//创建自动释放池 if (self.isCancelled) {//检测操作是否被取消 return; } //下载图片 [NSThread sleepForTimeInterval:5]; NSURL *nsurl = [NSURL URLWithString:self.imageUrl]; UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:nsurl]]; if (self.isCancelled) { return; } //回到主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //通知代理对象 if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownloadImage:)]) { [self.delegate downloadOperation:self didFinishDownloadImage:image]; } }]; }}
SDWebImage框架 的使用
// 图片url NSString *url = model.icon;//// [cell.imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:model.placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {//// NSLog(@"%@----------%d--------%@",image,cacheType,imageURL);// }];///Users/devzkn/Library/Developer/CoreSimulator/Devices/5A6E02FF-A156-455B-AE43-C207F4E7FBC4/data/Containers/Data/Application/B1E84598-BCD5-4943-9859-853F3B0BCF9B/Library/Caches [cell.imageView sd_setImageWithPreviousCachedImageWithURL:[NSURL URLWithString:url] andPlaceholderImage:model.placeholderImage options:SDWebImageProgressiveDownload | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) { NSLog(@" 下载进度%f---%@",receivedSize*1.0/expectedSize,url); } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { NSLog(@"%@----------%d--------%@",image,cacheType,imageURL); }]; //static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week/**内存管理*/@implementation AppDelegate- (void) applicationDidReceiveMemoryWarning:(UIApplication *)application{ SDWebImageManager *imageMgr = [SDWebImageManager sharedManager]; [imageMgr cancelAll]; [imageMgr.imageCache clearMemory];}
NSURLConnection 的使用
1、异步请求
- (IBAction)login:(UIButton *)sender { NSString *userName = self.userName.text; if (userName.length ==0) { //提示用户 [MBProgressHUD showError:@"请输入用户名"]; return; } NSString *pwd = self.pwd.text; if (pwd.length == 0) { //提示用户 [MBProgressHUD showError:@"请输入密码"]; return; } //创建get请求 //请求服务器--http://127.0.0.1:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON NSString *str = [[NSString stringWithFormat:@"http://127.0.0.1:8080/MJServer/login?username=%@&pwd=%@",userName,pwd] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:str]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSLog(@"%s---start",__func__); [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSLog(@"%@,%@",response,connectionError); if (connectionError || data == nil) { //发送请求失败 [MBProgressHUD showError:@"发送请求失败"]; } //解析json NSError *error ; NSDictionary *answer = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; if (error) { //解析失败 [MBProgressHUD showError:@"解析失败"]; return; } if (answer[@"success"]) { [MBProgressHUD showSuccess:answer[@"success"]]; }else if (answer[@"error"]){ [MBProgressHUD showError:answer[@"error"]]; } }];NSLog(@"%s----end",__func__);}
NSMutableURLRequest 的使用
设置请求体的数据类型
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:HSUrl(@"order")]; [request setHTTPMethod:@"post"]; /* 发送JSON数据 订单数据:{ "shop_id" : "1239098", "shop_name" : "lydia", "user_id" : "kevin"} */ NSDictionary *dict = @{@"shop_id":@"1239098",@"shop_name":@"lydia", @"user_id":@"kevin"}; [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil ]]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];//see http://www.iana.org/assignments/media-types/
常见问题
颜色的定义方法colorWithRed G B
NSString *color = @"0x00b47f";upButton.backgroundColor = [self backColor:color];- (UIColor *)backColor:(NSString *)color{long colorLong = strtoul([color cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);// 通过位与方法获取三色值int R = (colorLong & 0xFF0000 )>>16;int G = (colorLong & 0x00FF00 )>>8;int B = colorLong & 0x0000FF;//string转colorUIColor *wordColor = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0];return wordColor;}
URL的转码
#define HSUrl(path) [NSURL URLWithString:[[NSString stringWithFormat:@"%@%@",HSBaseUrl,path] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] //post 方式的时候 [request setHTTPBody:[[NSString stringWithFormat:@"username=%@&pwd=%@",userName,pwd] dataUsingEncoding:NSUTF8StringEncoding]];
阅读全文
0 0
- 23&24day 网络、cell的代码块,以及常见错误
- 代码的演进以及常见的设计错误
- 23&24day-网络
- 代码常见的错误
- iOS 中使用 XIB 自定义cell 的两种方法 以及 编译出现常见 的错误 ++++(xcode6.0之后)
- 11.1.1 重用常见的代码块
- Java study 06day-静态代码块
- Spring的AOP配置以及常见错误(内附代码)
- 阶段总结--业务系统代码中常见的异常错误总结以及避免方法
- vsftpd的常见错误以及解决办法
- DB2常见的错误以及解决方法
- 常见的内存错误以及如何避免
- c语言常见的错误,以及解决方法
- zxing的使用方法以及常见错误
- 常见的内存错误以及如何避免
- MySQL安装以及常见的安装错误
- 常见以及遇到的错误整理
- 关于tableview中cell高度不同,用代码生成cell时常出现的错误
- 32-从1到n整数中X出现的次数
- 软件测试风险分析列表-待完善
- MyEclipse中复制项目或修改项目名字出现问题
- hdu 4570 Multi-bit Trie 【区间dp】
- leetcode[Nim Game]
- 23&24day 网络、cell的代码块,以及常见错误
- 域间路由的安全性增强机制-FRA(快速路由证明)
- VisionPro--- CogGraphicLabel
- iOS 从0到1搭建高可用App框架(二)
- Python中利用set去除列表(list)重复元素
- 融云SDK设置头像与消息监听注意事项
- Cadence学习总结
- HealthKit读取步数、运动距离、已爬楼层等信息
- 简述极大似然估计