IOS多线程-线程间的通信

使用NSThread实现线程间的通信

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)download {
    // 1.图片地址
    NSString *urlStr = @"http://image1.mop.com/images/project14/2012-10-19/13506138571471411.jpg";
    NSURL *imageUrl = [NSURL URLWithString:urlStr];
    
    // 2.根据图片的地址下载图片的二进制数据
    NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
    
    // 3.设置图片
    UIImage *image = [UIImage imageWithData:imageData];
    
    // 4.回到主线程,刷新UI界面
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    
    NSLog(@"download --- %@", [NSThread currentThread]);
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self performSelectorInBackground:@selector(download) withObject:nil];
    
}

@end

实现效果

IOS多线程-线程间的通信_第1张图片
实现效果.png

⚠️注意!!!

如果点击屏幕发现不能正常下载图片,并且报以下错误的话

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

说明你没有允许网络服务,还需要在info.plist文件中增加如下设置


打开网络服务.png

你可能感兴趣的:(IOS多线程-线程间的通信)