MRC下block的循環(huán)引用

說明一下造成循環(huán)引用的場景,viewController持有某個view,view中持有block,block內(nèi)部引用vc,造成的循環(huán)引用。在arc的環(huán)境下使用__weak即可解決問題,但是mrc中不能使用weak關(guān)鍵字(其實是可以在項目配置中設(shè)置的,但是考慮到老項目一般都沒有開放mrc使用weak的配置,所以不使用weak),使用__block即可。

//view.h
@interface BlockView : UIView
@property(nonatomic, copy)void(^dismissCallback)(void);
@end

//view.m
@implementation BlockView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jk_tapAction)];
        [self addGestureRecognizer:tap];
        
        [tap release]; tap = nil;
    }
    return self;
}

- (void)dealloc{
    [super dealloc];
}

- (void)jk_tapAction{
    if (self.dismissCallback) {
        self.dismissCallback();
    }
    self.backgroundColor = [UIColor blueColor];
}

@end

//vc.m
@interface BlockViewController ()
@property(nonatomic, retain)UILabel *titleLabel;
@end

@implementation BlockViewController{
    BlockView *_redView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    self.titleLabel.text = @"title";
    [self.view addSubview:self.titleLabel];
    
    __block typeof(self) weakSelf = self;
    _redView = [[BlockView alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];
    _redView.backgroundColor = [UIColor redColor];
    _redView.dismissCallback = ^{
        //如果不使用weakSelf則無法進入dealloc
        weakSelf.titleLabel.text = @"changed";
    };
    [self.view addSubview:_redView];
}

- (void)dealloc{
    [_redView release]; _redView = nil;
    [_titleLabel release]; _titleLabel = nil;
    [super dealloc];
}

demo在這里https://gitee.com/Jack_1993/mrc_-playground
希望能夠?qū)υ赼rc時代開始做iOS的大家有幫助:)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容