weak strong dance

235 阅读1分钟

关于强弱引用,在Xcode7.3之前,仍然需要weak-strong dance,但是在7.3之后,就不需要在block里对self进行强引用了

@interface ViewController ()

@property (nonatomic, copy) NSString * name;

@property (nonatomic, copy) MyBlock demoBlock;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof (self) weakSelf = self;
    self.demoBlock = ^{
        //7.3之前的版本,会正常输出
        NSLog(@"%@", weakSelf.view);
        
        [NSThread sleepForTimeInterval:2.0];
        
        //7.3之前不会输出下面代码
        // 7.3 之后,就不需要强弱引用了.
        NSLog(@"%@", weakSelf.view);
    };
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.demoBlock();
    });
}

- (void)dealloc {
    NSLog(@"%s", __func__);
}

在7.2之前的weak-strong dance写法如下:

__weak typeof (self) weakSelf = self;
    self.demoBlock = ^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {  //这里对strongSelf进行了一个判断,是为了确保在在强引用weakSelf时,weakSelf不为nil
            //7.3之前的版本,会正常输出
            NSLog(@"%@", weakSelf.view);
            
            [NSThread sleepForTimeInterval:2.0];
            
            //7.3之前不会输出下面代码
            // 7.3 之后,就不需要强弱引用了.
            NSLog(@"%@", weakSelf.view);
        }
        
    };