美文网首页
IOS多线程-线程间的通信

IOS多线程-线程间的通信

作者: mr_young_ | 来源:发表于2017-03-06 12:35 被阅读167次

    使用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<UITouch *> *)touches withEvent:(UIEvent *)event {
        [self performSelectorInBackground:@selector(download) withObject:nil];
        
    }
    
    @end
    

    实现效果

    实现效果.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多线程-线程间的通信

          本文链接:https://www.haomeiwen.com/subject/puoygttx.html