实例解析iOS应用多线程开发中NSthread类的用法

2020-01-14 19:58:20刘景俊

3.在当前线程执行操作
复制代码
[self performSelector:@selector(run) withObject:nil];  

 

六、优缺点
1.优点:NSThread比其他两种多线程方案较轻量级,更直观地控制线程对象
2.缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销

七、下载图片的例子:
新建singeView app
新建项目,并在xib文件上放置一个imageView控件。按住control键拖到viewControll
er.h文件中创建imageView IBOutlet 
ViewController.m中实现:

复制代码
//  
//  ViewController.m  
//  NSThreadDemo  
//  
//  Created by rongfzh on 12-9-23.  
//  Copyright (c) 2012年 rongfzh. All rights reserved.  
//  
  
#import "ViewController.h"  
#define kURL @"http://www.easck.com/2/C/D/1_totogo2010.jpg"  
@interface ViewController ()  
  
@end  
复制代码   
@implementation ViewController  
  
-(void)downloadImage:(NSString *) url{  
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];  
    UIImage *image = [[UIImage alloc]initWithData:data];  
    if(image == nil){  
          
    }else{  
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];  
    }  
}  
  
-(void)updateUI:(UIImage*) image{  
    self.imageView.image = image;  
}  
  
  
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
      
//    [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:kURL];  
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage:) object:kURL];  
    [thread start];  
}  
  
- (void)didReceiveMemoryWarning  
{  
    [super didReceiveMemoryWarning];