美文网首页
iOS 控制器的实例 的block循环引用

iOS 控制器的实例 的block循环引用

作者: guoshengboy | 来源:发表于2017-04-05 11:08 被阅读0次

    当变量为控制器的实例时 也会出现循环引用例如abc
    @interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
    {
    UITableView *_tableView;
    NSString *abc;
    }

    1.如果此时的block不属于self 则直接赋值(在VC在dealloc前 必须要销毁block回调 否则内存泄漏) 例如添加在keywindow上的View:

    • (void)viewDidLoad {
      [super viewDidLoad];

      AView *view = [[AView alloc] init];
      view.frame = CGRectMake(100, 100, 100, 100);
      view.backgroundColor = [UIColor redColor];
      view.abc = ^(NSString *aaa){

        abc = aaa;
      

      };
      AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
      UIWindow *keywindow = delegate.window;
      [keywindow addSubview:view];
      [view removeFromSuperview];

    //这样写block也不属于self
    void(^foo)(NSStringstr)= ^(NSString str){

        abc = str;
    };
    foo(@"1111");
    

    }

    2.如果此时的block属于self 则要写方法赋值赋值 例如添加在self.view上的View:

    • (void)viewDidLoad {
      [super viewDidLoad];

      __weak typeof(self) weakSelf = self;
      AView *view = [[AView alloc] init];
      view.frame = CGRectMake(100, 100, 100, 100);
      view.backgroundColor = [UIColor redColor];
      view.abc = ^(NSString *aaa){
      [weakSelf setAbc:aaa];
      };
      [self.view addSubview:view];
      }

    -(void)setAbc:(NSString *)a{

    abc = a;
    

    }

    相关文章

      网友评论

          本文标题:iOS 控制器的实例 的block循环引用

          本文链接:https://www.haomeiwen.com/subject/vkehbttx.html