iOS 多线程总结(一)

1.线程间的通信:

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array NS_AVAILABLE(10_5, 2_0);

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);

// equivalent to the first method with kCFRunLoopCommonModes

- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg NS_AVAILABLE(10_5, 2_0);//后台运行。


2.简单的使用


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {


    [self performSelectorInBackground:@selector(downloadImage) withObject:nil];

}


#pragma mark- 下载图片

- (void)downloadImage

{

    // 子线程里面的runloop默认不开启, 也就意味不会自动创建自动释放池, 子线程里面autorelease的对象 就会没有池子可放。 也就意味后面没办法进行释放。 造成内存泄露

    // 所以需要手动创建

    @autoreleasepool {

   

        NSLog(@"%@", [NSThread currentThread]);

        

        // 1. url, 确定一个网络上的资源路径

        NSURL *url = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/image/pic/item/5366d0160924ab1828b7c95336fae6cd7b890b34.jpg"];

        

        // 2. 通过url可以下载对应的网络资源, 网络资源传输的都是二进制

        NSData *data = [NSData dataWithContentsOfURL:url];

        

        // 3. 二进制转成图片

        UIImage *image = [UIImage imageWithData:data];

        

        // 4. 把图片显示到iconView

    //    self.iconView.image = image;

        // 在这里需要把数据传到主线程,在主线程更新UI

    //    1.

        [self performSelectorOnMainThread:@selector(downloadFinish:) withObject:image waitUntilDone:NO];

        //2. [self performSelector:@selector(downloadFinish:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];

        //3.

    //    [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];

        

        // waitUntilDone:表示是否等待@selector(setImage:) 方法执行完成

        // 如果是YES,就等待setImage在其他线程执行结束,再往下执行

        NSLog(@"完成!!");

    }

}


- (void)downloadFinish:(UIImage *)image

{

    NSLog(@"%s---%@", __func__, [NSThread currentThread]);

    self.iconView.image = image;

//    [self.iconView setImage:image];

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值