iOS-block程序员iOS进阶指南

Block循环引用解决办法

2016-03-30  本文已影响305人  Z了个L

// 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(@"%@对象销毁",self);
}

/**
 *  说明,如果_block里面保存的代码只是在主线程执行,而且内部保存的代码用到外界的self
    那么,必须得__weak typeof(self) weakSelf = self;然后用weakSelf变量就可以了,
    放在循环引用,
    如果保存的代码还得在子线程或者主线程延时之后做一些操作的话,还得用到self的话,首先第一步是
    __weak typeof(self) weakSelf = self;第二步在保存的代码位置写__strong typeof(weakSelf) strongSelf = weakSelf;然后用strongSelf变量就可以了
 */

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

    // Block循环引用,跟block调用没有关系
    // block只要访问外部强指针对象变量,就会对这个变量进行强引用.
    __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.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


上一篇下一篇

猜你喜欢

热点阅读