当变量为控制器的实例时 也会出现循环引用例如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;
}
网友评论