iPhone开发【十五】多线程开发之NSThread——异步下载图片

转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/8220819  作者:张燕广

实现的功能:1)演示多线程NSThread开发;2)子线程中执行下载图片工作,图片下载完成前显示等待框;

关键词:多线程 NSThread 等待框

1、新建视图控制器ViewController(不带xib),作为根视图控制器,通过ViewController的-(void)loadView方法构建UI,ViewController.h如下:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>

@property(strong,nonatomic)UIImageView *imageView;
@property(strong,nonatomic)NSMutableData *buffer;
@property Boolean done;
@end


ViewController.m如下:

#import "ViewController.h"
@implementation ViewController
@synthesize imageView;
@synthesize buffer;
@synthesize done;

-(void)loadView{
    //初始化视图
    [self initViews];
    
    NSString *url = @"http://avatar.csdn.net/4/D/5/1_m_changgong.jpg";
    //在子线程执行图片下载操作
    [NSThread detachNewThreadSelector:@selector(downloadAppImage:) toTarget:self withObject:url];
}

//初始化视图组件
-(void)initViews{
    CGRect frame = [UIScreen mainScreen].applicationFrame;
    imageView = [[UIImageView alloc]initWithFrame:frame];
    self.view = imageView;
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

//下载图片
-(void)downloadAppImage:(NSString *) url{
    //展示等待框
    [self showWaiting];
    
    done = NO;
    //初始化缓冲区
    buffer = [NSMutableData data];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    //设置请求及连接
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLConnection *connnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if(connnection!=nil){
        while(!done){
             //NSLog(@"doing..");
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    }
    //生成UIImage实例
    UIImage *img = [UIImage imageWithData:buffer];
    //通知主线程
    [self performSelectorOnMainThread:@selector(showImage:) withObject:img waitUntilDone:NO]; 
    
    request = nil;
    connnection = nil;
}

//填充图片
-(void)showImage:(UIImage *)img{  
    [self.imageView setImage:img];
    
    //关闭等待框
    [self hiddenWaiting];
}

-(void)httpConnectEnd{
    NSLog(@"httpConnectEnd");
}

-(void)httpConnectEndWithError{
    [self hiddenWaiting];
    
    NSLog(@"httpConnectEndWithError");
}

//展示等待框
-(void)showWaiting{
    int width = 32;
    int height = 32;
    CGRect frame = CGRectMake(0, -20, 320, 480);
    int x = frame.size.width;
    int y = frame.size.height;
    NSLog(@"x=%d,y=%d",x,y);
    
    frame = CGRectMake((x-width)/2, (y-height)/2, width, height);
    UIActivityIndicatorView *progressInd = [[UIActivityIndicatorView alloc]initWithFrame:frame];
    [progressInd startAnimating];
    progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    
    frame = CGRectMake((x-70)/2, (y-height)/2+height, 80, 20);
    UILabel *waitinglabel = [[UILabel alloc]initWithFrame:frame];
    waitinglabel.text = @"正在下载应用程序图片...";
    waitinglabel.textColor = [UIColor redColor];
    waitinglabel.font = [UIFont systemFontOfSize:15];
    waitinglabel.backgroundColor = [UIColor clearColor];
    
    frame = CGRectMake(0, -20, 320, 480);
    UIView *waitingView = [[UIView alloc]initWithFrame:frame];
    waitingView.backgroundColor = [UIColor blackColor];
    waitingView.alpha = 0.7;
    
    [waitingView addSubview:progressInd];
    [waitingView addSubview:waitinglabel];
    
    [waitingView setTag:110];//设置tag
    [self.view addSubview:waitingView];
}

//隐藏等待框
-(void)hiddenWaiting{
    //根据tag找到waitingView
    [[self.view viewWithTag:110]removeFromSuperview];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark NSURLConnection Delegate methods
//不执行缓存
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
    return nil;
}

//连接发生错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self performSelectorOnMainThread:@selector(httpConnectEndWithError) withObject:self waitUntilDone:NO];
    [buffer setLength:0];
}

//接收数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [buffer appendData:data];
}

//下载完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //NSLog(@"connectionDidFinishLoading");
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO]; 
    //self.done = YES;
}

@end

2、运行效果如下:

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在网络编程中,多线程编程是一种常用的技术,可以提高程序的并发性和性能。下面是一些关于多线程编程的常用方法和注意事项: 1. NSThreadNSThread是iOS中最底层的线程类,它可以通过类方法或实例方法来创建线程。使用NSThread可以设置线程的名称、优先级,以及控制线程的睡眠和退出等操作。 2. 线程调度:在多线程编程中,多个线程会并发运行,但线程的执行顺序是由CPU调度器决定的,程序员无法控制。多个线程会同时竞争CPU资源,谁先抢到资源谁就先执行,所以多线程的执行顺序是随机的。 3. 多线程的创建:在iOS开发中,常用的多线程编程方式有三种:NSThread、GCD和NSOperation。NSThread是最底层的线程类,可以直接操作线程的各种属性和方法。GCD(Grand Central Dispatch)提供了一种高效的并发编程模型,可以通过队列来管理任务的执行。NSOperation是基于GCD的更高层次的封装,提供了更多的控制和管理线程的功能。 4. 线程的创建顺序:在多线程编程中,并不能保证哪个线程会先运行,即无法确定新创建的线程或调用线程哪个会先执行。新创建的线程可以访问进程的地址空间,并继承调用线程的浮点环境和信号屏蔽字,但挂起信号集会被清除。 总结来说,多线程编程是一种提高程序并发性和性能的技术,在网络编程中尤为重要。通过使用NSThread、GCD或NSOperation等方法,可以实现多线程的创建和管理。然而,程序员无法控制线程的执行顺序,因为线程的调度是由CPU调度器决定的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [IOS之多线程基础(OC)](https://blog.csdn.net/yong_19930826/article/details/105857055)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [UNIX环境高级编程笔记](https://blog.csdn.net/w_x_myself/article/details/128613534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值