當(dāng)變量為控制器的實(shí)例時(shí) 也會(huì)出現(xiàn)循環(huán)引用例如abc
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
UITableView *_tableView;
NSString *abc;
}
1.如果此時(shí)的block不屬于self 則直接賦值(在VC在dealloc前 必須要銷毀block回調(diào) 否則內(nèi)存泄漏) 例如添加在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.如果此時(shí)的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;
}