block循环引用

block可以造成循环引用,导致对象不能释放,造成内存泄露。

所以在使用的时候,要用__block 来对变量或属性进行修饰。
而且block的释放跟一般的变量不一样

布局为一个根视图控制器,一个firstViewcontroller。这里仅显示了firstViewcontroller的代码

#import "FirstViewController.h"

typedef void(^BLOCK)(NSString *);

@interface FirstViewController ()

{
    UILabel *label;
}

@property(nonatomic,copy)BLOCK block;

@end

@implementation FirstViewController


- (void)dealloc
{


#pragma mark-----------------block的释放跟变量不一样
    Block_release(_block);



    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];


    label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];


    self.view.backgroundColor = [UIColor cyanColor];

    NSLog(@"++++++%lu",[_block retainCount]);

    NSLog(@"-------%lu",self.retainCount);


    __block FirstViewController *firstVC = self;

    //在block中如果用到了self或者当前类的实例变量,一定要记得用__block修饰,否则会造成循环引用。
    self.block = ^void(NSString *text){
        firstVC.title = text;
    };

    NSLog(@"++++++%lu",[_block retainCount]);

    NSLog(@"-------%lu",self.retainCount);


    _block(@"First");


    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值