Block循環(huán)引用解決辦法

  • ModalViewController

// ModalViewController.h
#import <UIKit/UIKit.h>

@interface ModalViewController : UIViewController

@end


// ModalViewController.m
#import "ModalViewController.h"

@interface ModalViewController ()

@property (nonatomic ,strong) void(^block)();

@end

@implementation ModalViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc
{
    NSLog(@"%@對(duì)象銷毀",self);
}

/**
 *  說明,如果_block里面保存的代碼只是在主線程執(zhí)行,而且內(nèi)部保存的代碼用到外界的self
    那么,必須得__weak typeof(self) weakSelf = self;然后用weakSelf變量就可以了,
    放在循環(huán)引用,
    如果保存的代碼還得在子線程或者主線程延時(shí)之后做一些操作的話,還得用到self的話,首先第一步是
    __weak typeof(self) weakSelf = self;第二步在保存的代碼位置寫__strong typeof(weakSelf) strongSelf = weakSelf;然后用strongSelf變量就可以了
 */

 
- (void)viewDidLoad {
    [super viewDidLoad];
    int a = 0;

    // Block循環(huán)引用,跟block調(diào)用沒有關(guān)系
    // block只要訪問外部強(qiáng)指針對(duì)象變量,就會(huì)對(duì)這個(gè)變量進(jìn)行強(qiáng)引用.
    __weak typeof(self) weakSelf = self;

    _block = ^{

        __strong typeof(weakSelf) strongSelf = weakSelf;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            NSLog(@"延遲打印%@",strongSelf);

        });

    };

    _block();
}

@end


  • ViewController

// ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

// ViewController.m
#import "ViewController.h"
#import "ModalViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    ModalViewController *modalVc = [[ModalViewController alloc] init];

    modalVc.view.backgroundColor = [UIColor redColor];

    [self presentViewController:modalVc animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

}

@end


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

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

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