23&24day 网络、cell的代码块,以及常见错误
2017-07-10 10:49
369 查看
代码块
一、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/[/code]常见问题
颜色的定义方法colorWithRed G BNSString *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转color UIColor *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]];
相关文章推荐
- 常见的网络请求错误,以及建议
- iOS 中使用 XIB 自定义cell 的两种方法 以及 编译出现常见 的错误 ++++(xcode6.0之后)
- 玩转开发板--常见的网络下载错误归纳以及注意事项
- Oracle数据库的网络连接配置以及一些常见错误信息解决方法
- sql server2000 安装过程中"一般性网络错误"问题的解决
- 由于空格引起的xml错误之The processing instruction target matching "[xX][mM][lL]" is not allowed以及the markup in the document prec
- sql 常见错误以及解决方法
- python 常见错误类型以及继承关系
- HTTP协议中POST、GET、HEAD、PUT等请求方法以及一些常见错误
- Xcode7常见编译错误以及解决方法汇总(持续补充)
- SQL Server2005用新建用户名登录提示“该用户与可信 SQL Server 连接无关联” 以及SQL Server2005常见错误及解决方案
- git 基础以及常见错误
- IOCP在网络应用中常见错误分析
- 尝试从 Web 项目中访问网络文件时服务器返回的常见错误的列表
- UITableView 的一个常见错误'unable to dequeue a cell with identifier Cell - must register a nib or a class f
- VC常见错误:>nafxcwd.lib(afxmem.obj) : error LNK2005
- ios常见错误—— -[_NSString absoluteURL](请求网络图片)
- java常见错误以及可能原因
- 转:IOCP在网络应用中常见错误分析
- 常见的内存错误以及相应的对策