Block引用全局变量处理(内存泄露问题)
Block正确的写法:往后只要是引用了全局的变量等,全部变成弱指针
************************************************************************************************
*
* Block的写法:往后在使用Block的时,如果引用了BLock外部的变量,一定将这个变量更换
* 在原始变量的基础上加上: __unsafe_unretained 或者 __weak
* eg: self 可以写成: __unsafe_unretained FLShareViewController *share = self; 不推荐
* 或者写成: __weak FLShareViewController *share = self; 不推荐
* 写成: __weak typeof(self) share = self; 推荐,用不了就用第一种
*
************************************************************************************************
Block的内存泄露:
在设置界面里面,有一个回调的Block,而在这个Block中会引用外部的属性,而Block是copy类型,但是又因为引用了全局的强引用,
如使用了self这种写法,回头controller消失了,但造成了dealloc生命周期方法不会调用,造成了互相引用,因此会造成内存的泄露
解决的办法是:不用采用强指针
那怎么才能不使用强指针的self
///////////////////////////////////////////////////////////////
代码:不推荐
__unsafe_unretained FLShareViewController *share = self;
FLSettingItem *itemSms = [FLSettingArrowItem itemWithIcon:@"MailShare" title:@"短信分享" destVcClass:nil];
itemSms.option = ^{
/**
* 将内部所有使用self的地方都改成使用share
*/
[share ];
};
///////////////////////////////////////////////////////////////
代码:不推荐
__weak FLShareViewController *share = self;
FLSettingItem *itemSms = [FLSettingArrowItem itemWithIcon:@"MailShare" title:@"短信分享" destVcClass:nil];
itemSms.option = ^{
/**
* 将内部所有使用self的地方都改成使用share
*/
//[share ...];
};
///////////////////////////////////////////////////////////////
推荐:
__weak typeof(self) share = self;
FLSettingItem *itemSms = [FLSettingArrowItem itemWithIcon:@"MailShare" title:@"短信分享" destVcClass:nil];
itemSms.option = ^{
/**
* 将内部所有使用self的地方都改成使用share
*/
//[share ...];
};
///////////////////////////////////////////////////////////////
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
