block解决循环引用(二)

接着上一遍,这里首先讲一下
block的反向传值

这里写图片描述

ViewController和ViewController1
//ViewController1里面
typedef  void(^MyBlock)(NSString *str);
@interface ViewController1 : UIViewController
@property (nonatomic,copy) MyBlock myBlock;


ViewController里面的代码
 //1.不会循环引用
        ViewController1 *vc = [[ViewController1 alloc]init];

        vc.myBlock = ^(NSString *str) {
            NSLog(@"%@",str);
            NSLog(@"%@",self.str);
            NSLog(@"%@",self.str = str);

        };
        [self.navigationController pushViewController:vc animated:YES];

//ViewController1 里面进行反向传值
 if (self.myBlock) {
        self.myBlock(@"20");
    }

    [self.navigationController popViewControllerAnimated:NO];
//2.会循环引用
       ViewController1 *vc = [[ViewController1 alloc]init];

        vc.myBlock = ^(NSString *str) {

            NSLog(@"%@",vc.VC1Str);
            NSLog(@"%@",vc);


        };
        [self.navigationController pushViewController:vc animated:YES];



    //3.解除循环引用
        ViewController1 *vc = [[ViewController1 alloc]init];
        __weak typeof(vc) weakSelf = vc;

        vc.myBlock = ^(NSString *str) {
            NSLog(@"%@",weakSelf.VC1Str);
            NSLog(@"%@",weakSelf);

        };
        [self.navigationController pushViewController:vc animated:YES];

block作为参数使用
这种只能在方法内部进行调用,用于回调和传值等

//这里声明了一个Person,里面有一个方法
typedef void (^Block) (NSString * str);
@interface Person : NSObject
-(void)testBlock:(Block)myBlock;

//在ViewController里面倒入一下
@interface ViewController ()
@property (nonatomic,strong)Person *person;
 [self.person testBlock:^(NSString *str) {

        NSLog(@"%@",str);
        NSLog(@"%@",self.str);
        NSLog(@"%@",self.str = str);
        NSLog(@"%@",self.person.personStr);
    }];
//像这种block是在方法中 ,以上在block里面的操作,都不会造成循环引用。这种block不属于对象的属性,并没有被对象持有,也并不会引起循环引用。
//AFNetworking里面也是这种操作,很多时候我们也会去这样使用。

block的注意点

  1.在block内部使用外部指针且会造成循环引用情况下,需要用到_weak修饰外部指针
     __weak typeof(self) weakSelf = self;

     2.在block内部如果调用了延时函数还使用了弱指针会取不到指针,因为已经被销毁了,需要在block内部再将弱指针重新强引用一下。
     __strong typeof(self) strongSelf = weakSelf;

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     [... test];
     });
     3.如果需要在block内部改变外部栈区变量的话,需要在用__block修饰外部变量

以上就是全部了,感觉有用的上个星,附上demo下载地址
如有疑问,欢迎跟我沟通,qq:2877025939

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值