循环引用:
1. 添加点击事件:
__weak typeof(self) weakSelf = self;
[attributedString addAttribute:@"target" value:weakSelf range:[attributedString gange]];
这句话会可能有循环引用问题,虽然用了weakSelf,但是调用addAttributed
方法后,经测试attributedString 会对self进行强引用,
这时候,如果self
的subview
持有 attributedString
,那么会产生循环引用问题。
解决方案:(在AttributedString 的 extension中添加这个方法)
.h
typedef void(^SingleCallBack)(void);
/**
* @brief 简要描述.
*
* 详细描述或其他.
* @warning 警告:中间的代码在引用外部的变量的时候,需要用weak修饰 否则会导致循环引用
*
* 代码:
*
* [NSMutebleAttributedString 对象]
* .registerSingleClick(^{
* 注意中间引用对象 需要用weak修饰
* [weakSelf singleEventFunc];
* });
*/
- (NSMutableAttributedString *(^)(SingleCallBack singleCallBack)) registerSingleClick;
.m
- (NSMutableAttributedString *(^)(SingleCallBack singleCallBack)) registerSingleClick {
__weak typeof (self) weakSelf = self;
return ^(SingleCallBack singleCallBack) {
if (singleCallBack) {
[weakSelf addAttribute:k_NSMutableAttributedStringRegisterSingleCliekWithBlock value:singleCallBack range:[weakSelf getRange]];
}
return weakSelf;
};
}
示例
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"register event"];
__weak typeof (self)weakSelf = self;
attributedString.registerSingleClick(^{
attributedStringM.font([UIFont systemFontOfSize:20]);
[weakSelf dismissViewControllerAnimated:true completion:nil];
});