TextFieldInputView *inputView = [[TextFieldInputView alloc] initWithItems:_items];
UITextField *field = [[UITextField alloc] init];
field.inputView = inputView;
@weakify(self);
[inputView setSelection:^(NSInteger index) {
@strongify(self);
[field resignFirstResponder];
field.text = [NSString stringWithFormat:@"%@%%",self.items[index]];
self.selectedIndex = index;
}];
产生循环引用的原因分析:field强引用 inputView, inputView的block强引用field,当所有外部的对field的引用清除后,此刻inputView的block还保留对field的引用,而inputView的block的释放依赖于inputView引用计数为0,inputView的释放依赖于field引用计数为0,此时就形成了保留环,导致file和inputView都无法被释放!!
解决思路:
传入block时,将field的强引用改为弱引用,而在执行block期间保持对field的强引用,保证在执行block期间,field不会被释放,一旦block代码执行完毕,block里对field的强引用会被自动清除。
@weakify(field);
@weakify(self);
[inputView setSelection:^(NSInteger index) {
@strongify(self);
@strongify(field);
[field resignFirstResponder];
field.text = [NSString stringWithFormat:@"%@%%",self.items[index]];
self.selectedIndex = index;
}];
网友评论