代码块
一、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转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]];
作者:u011018979 发表于2017/7/10 10:49:40 原文链接
阅读:141 评论:0 查看评论