多线程 block中self 强引用问题

#import "ViewController.h"网络

 

@interface ViewController ()并发

 

// 定义一个全局的队列属性.方便在任何方法中均可以使用这个Queue

@property (nonatomic,strong) NSOperationQueue *queue;async

 

// UI 控件用 weak 和 Strong 都没有问题.atom

// 在开发中,基本会见到全部的UI控件都是用 Strong来作的.spa

// UI控件通常不要用懒加载的方式加载.UI控件与用户是对应的.UI控件以外的,能用懒加载就用懒加载.线程

@property (nonatomic,strong) UIButton *button;队列

@end内存

 

@implementation ViewController开发

 

// 懒加载

-(NSOperationQueue *)queueget

{

    if (!_queue) {

        _queue = [[NSOperationQueue alloc] init];

        

        // 设置最大并发数.最多同时只能开启6条线程.

        [_queue setMaxConcurrentOperationCount:6];

        

        // 网络因素:

    }

    return _queue;

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

  

}

 

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

{

    

    // 这里直接在Block 中使用 self 会形成循环引用. Block使用的注意点之一:循环引用.

    //  __weak typeof(self) wself = self; wself 就是 self 的弱引用写法.

    

    // GCD中的任务都是封装在Block中,若是GCD中的Block中出现了 self,会形成循环引用吗?

    //

    

//    dispatch_async(dispatch_get_main_queue(), ^{

//        [self test];

//    }); 会形成循环引用吗? 不会形成循环引用,由于 self 对这个Block 没有强引用.

 

    // 建立操做

    __weak typeof(self) wself = self;

    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

        

        // Block中出现self .Block 对 self 是强引用.

        [wself test];

    }];

    

    // 将操做添加到队列中.

    // self.queue 对 op 就是强引用.

    [self.queue addOperation:op];

}

 

// 接收到内存警告的时候,就会调用.

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    

    // 取消操做.有两个方法:

    // 1> 操做队列取消全部的操做

    

    // 取消全部操做. 对于取消的操做,没法再次恢复.

    [self.queue cancelAllOperations];

    

    // 2> 单个操做能够取消.NSOperation的方法.

    

    

}

 

- (void)test1

{

    // NSOperation 高级操做 : 暂停/恢复

    // 这两个方法,通常用在与用户交互的时候.

    

    // 暂停队列中的全部操做

    [self.queue setSuspended:YES];

    

    // 恢复队列中的全部操做

    [self.queue setSuspended:NO];

}

 

 

- (void)test

{

    NSLog(@"下载任务(很是耗时)------------%@",[NSThread currentThread]);

}

 

@end

相关文章
相关标签/搜索